package o2o.web.actions.order.postman;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jinyou.utils.common.*;
import com.jinyou.utils.common.dao.GeoAddressDetail;
import com.jinyouapp.common.tools.jms.model.JMSNotify;
import jPush.dao.JPushMessage;
import map.HttpRequest;
import notice.dao.NoticeType;
import o2o.business.sms.JYSmsSeverBusiness;
import o2o.business.sms.data.SMS_TYPE;
import o2o.cache.agent.AgentOrderOverTimeMemory;
import o2o.cache.company.postman.PostCompanyMemory;
import o2o.cache.order.*;
import o2o.cache.order.postman.PostmanOrderMemoryMan;
import o2o.cache.postman.CityPostmanMemory;
import o2o.cache.postman.PostmanPositionMemory;
import o2o.cache.shop.ShopManagerRelationMemory;
import o2o.cache.shop.ShopMemory;
import o2o.cache.sys.SysConfigDepositMemory;
import o2o.cache.user.UserInfoMemory;
import o2o.cache.user.UserOnlineImpl;
import o2o.cache.wallet.UserWalletMemory;
import o2o.config.dao.UserDaoSql;
import o2o.config.dao.utils.DaoUtils;
import o2o.config.dao.utils.Expression;
import o2o.config.dao.utils.QueryCondition;
import o2o.config.jms.config.JMSTypeContent;
import o2o.config.jms.sender.JmsSender;
import o2o.dao.PO.PojoTables;
import o2o.dao.PO.agent.OrderOverTimeInfo;
import o2o.dao.PO.common.ResultInfo;
import o2o.dao.PO.common.UserType;
import o2o.dao.PO.company.postman.PostCompanyInfo;
import o2o.dao.PO.device.door.DeviceCompanyContact;
import o2o.dao.PO.order.*;
import o2o.postman.model.CityPostman;
import o2o.dao.PO.postman.POSTMAN_TYPE;
import o2o.dao.PO.postman.PostmanPositionInfo;
import o2o.dao.PO.shop.SHOP_SERIESSALE_TYPE;
import o2o.company.model.ShopInfo;
import o2o.dao.PO.sys.SysSettingValueKey;
import o2o.dao.PO.user.UserInfo;
import o2o.dao.PO.wallet.UserWallet;
import o2o.delivery.service.DeliveryOrderTask;
import o2o.system.data.POSTMAN_IN_CITY_OR_AGENT_DATA;
import o2o.system.data.SYS_CONFIG_PATH;
import o2o.system.data.SYS_SETTINGS;
import o2o.task.mixComTel.MixComTelTask;
import o2o.utils.CommonUtils;
import o2o.web.actions.notice.Notice;
import o2o.web.actions.order.OrderMan;
import o2o.web.actions.order.thread.OverOrderThread;
import o2o.web.actions.pay.OrderPay;
import o2o.web.actions.sys.GrabOrderModeMan;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Set;

//配送员订单管理
@Controller
public class PostmanOrderController {
    @Autowired
    private DeliveryOrderTask deliveryOrderTask;

    //----------------------------配送员

    //配送员抢单
    @RequestMapping(method = RequestMethod.POST, value = "/postman/order/grab")
    @ResponseBody
    public String order_postman_new_list_grab(String token, String sysAppKey, Long companyId, String orderNo) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        CityPostman postman = CityPostmanMemory.getInstance().getPostman(user.getUsername());
        if (null == postman) {
            return AjaxResult.errorResult("未查询到您的信息，无法操作");
        }

        //0 锁定  1未锁定
        if (null != postman.getIsLock() && 0 == 1 - postman.getIsLock()) {
            return AjaxResult.errorResult("您已被锁定，无法接单");
        }

        if (ValidateUtil.isNotAbsInteger(postman.getIsWork())) {
            return AjaxResult.errorResult("您无法接单，请先上班");
        }
        if (0 == postman.getIsWork()) {
            return AjaxResult.errorResult("请先上班");
        }

        if (null != SYS_SETTINGS.POSTMAN_MUST_VERIFY && 0 == 1 - SYS_SETTINGS.POSTMAN_MUST_VERIFY
                && (null == postman.getIsVerify() || 0 != 1 - postman.getIsVerify())) {
            return AjaxResult.errorResult("您尚未通过认证，请先去认证");
        }
        if (null != SYS_SETTINGS.POSTMAN_MUST_VERIFY_FACE && 0 == 1 - SYS_SETTINGS.POSTMAN_MUST_VERIFY_FACE) {
            if (null != user.getIsCert() && 0 == 1 - user.getIsCert()) {
                //已认证
            } else {
                return AjaxResult.errorResult("未通过实名认证，请先去认证");
            }
        }
        if (SYS_SETTINGS.CUSTOM_SYSTEM_TYPE == 1 && ValidateUtil.isNotID(companyId)) {
            return AjaxResult.errorResult("公司id不能为空");
        }
        if (null != SYS_SETTINGS.POSTMAN_MUST_DEPOSIT && 0 == 1 - SYS_SETTINGS.POSTMAN_MUST_DEPOSIT) {
            // 必须缴纳
            //验证押金金额是否满足
            UserWallet userWallet = UserWalletMemory.getInstance().getWallet(user.getUsername());
            if (null == userWallet) {
                return AjaxResult.errorResult("您还未缴纳押金，请先缴纳押金");
            }
            if (null == userWallet.getDepositMoney() || userWallet.getDepositMoney() <= 0) {
                return AjaxResult.errorResult("您还未缴纳押金，请先缴纳押金！");
            }
            //必须缴纳的押金金额
            Double money = SysConfigDepositMemory.getInstance().getByType(UserType.POSTMAN);
            if (null == money) {
                money = 0d;
            }

            if (JYMathDoubleUtils.sub(userWallet.getDepositMoney(), money) < 0) {
                return AjaxResult.errorResult("您缴纳的押金不足，请先缴纳押金");
            }
        }

        // 排队抢单
        if (PostmanGrabMemory.getInstance().hasGrabed(orderNo)) {
            return AjaxResult.errorResult("排队抢单中，请重试");
        } else {
            PostmanGrabMemory.getInstance().addGrab(orderNo, user.getUsername());
        }

        OrderInfo orderInfo = OrderInfoMemory.getInstance().getOrderInfo(orderNo);
        if (null == orderInfo) {
            PostmanGrabMemory.getInstance().removeGrab(orderNo);
            return AjaxResult.errorResult("当前订单不存在");
        }

        if (ValidateUtil.isNotNull(orderInfo.getPostManUsername())) {
            PostmanGrabMemory.getInstance().removeGrab(orderNo);
            return AjaxResult.errorResult("该订单已被抢");
        }
        // 验证当前系统抢单模式
        // 若是抢单模式为仅调度模式则骑手不能抢单，只能接单
//        if (SYS_SETTINGS.GRAB_ORDER_MODE != null && SYS_SETTINGS.GRAB_ORDER_MODE == GRAB_ORDER_MODE.ONLY_DISPATCH_MODE) {

        if (GrabOrderModeMan.getGrabOrderMode(orderInfo.getAgentId()) == GRAB_ORDER_MODE.ONLY_DISPATCH_MODE) {
            PostmanGrabMemory.getInstance().removeGrab(orderNo);
            return AjaxResult.errorResult("当前系统仅调度模式,无法抢单");
        }

        // 判断是不是子订单 是的话 不让其抢
        if (OrderMan.isMultipleSonOrder(orderNo)) {
            PostmanGrabMemory.getInstance().removeGrab(orderNo);
            return AjaxResult.errorResult("您不可以直接抢子订单");
        }


        // 抢单数量限制
        if (!canGrabOrder(user.getUsername(), orderInfo.getAgentId(), orderNo)) {
            PostmanGrabMemory.getInstance().removeGrab(orderNo);
//            return AjaxResult.errorResult("您有未完成订单，无法继续抢单");
            return AjaxResult.errorResult("您接单数已达上限，如需接单请联系管理员");
        }


        //验证抢单范围
        if (null != SYS_SETTINGS.CHECK_POSTMAN_GRAB_RANGE && SYS_SETTINGS.CHECK_POSTMAN_GRAB_RANGE > 0) {//验证配送员抢单范围 0不验证 1验证取货地址 2验证收货地址
            if (null != SYS_SETTINGS.DELIVERY_RANGE && SYS_SETTINGS.DELIVERY_RANGE > 0) {
                PostmanPositionInfo positionInfo = PostmanPositionMemory.getInstance().get(postman.getId());
                if (null == positionInfo) {
                    PostmanGrabMemory.getInstance().removeGrab(orderNo);
                    return AjaxResult.errorResult("未定位到您的位置，无法抢单");
                }
                if (0 == 1 - SYS_SETTINGS.CHECK_POSTMAN_GRAB_RANGE) {//1验证取货地址
                    if (ValidateUtil.isAbsDouble(positionInfo.getLat()) && ValidateUtil.isAbsDouble(positionInfo.getLng())
                            && ValidateUtil.isAbsDouble(orderInfo.getLat()) && ValidateUtil.isAbsDouble(orderInfo.getLng())) {
                        Double distinct = Geohash.distance(positionInfo.getLat(), positionInfo.getLng(), orderInfo.getLat(), orderInfo.getLng());
                        if (ValidateUtil.isNotAbsDouble(distinct)) {
                            PostmanGrabMemory.getInstance().removeGrab(orderNo);
                            return AjaxResult.errorResult("未获取到距离，无法抢单");
                        }
                        if (distinct - SYS_SETTINGS.DELIVERY_RANGE > 0) {
                            PostmanGrabMemory.getInstance().removeGrab(orderNo);
                            return AjaxResult.errorResult("您已超出可接单范围");
                        }
                    }
                } else if (0 == 2 - SYS_SETTINGS.CHECK_POSTMAN_GRAB_RANGE) {//2验证收货地址
                    if (ValidateUtil.isAbsDouble(positionInfo.getLat()) && ValidateUtil.isAbsDouble(positionInfo.getLng())
                            && ValidateUtil.isAbsDouble(orderInfo.getShopLat()) && ValidateUtil.isAbsDouble(orderInfo.getShopLng())) {
                        Double distinct = Geohash.distance(positionInfo.getLat(), positionInfo.getLng(), orderInfo.getShopLat(), orderInfo.getShopLng());
                        if (ValidateUtil.isNotAbsDouble(distinct)) {
                            PostmanGrabMemory.getInstance().removeGrab(orderNo);
                            return AjaxResult.errorResult("未获取到距离，无法抢单");
                        }
                        if (distinct - SYS_SETTINGS.DELIVERY_RANGE > 0) {
                            PostmanGrabMemory.getInstance().removeGrab(orderNo);
                            return AjaxResult.errorResult("您已超出可接单范围");
                        }
                    }
                }
            }
        }

        int oStatus = ORDER_STATUS.POSTMAN_SURE;
        //判断订单状态  是否可以抢单
        if ((ORDER_STATUS.SHOP_SURE != orderInfo.getOrderStatus() && ORDER_STATUS.POSTMAN_REFUSED != orderInfo.getOrderStatus() && ORDER_STATUS.SHOP_READY != orderInfo.getOrderStatus() && (null != orderInfo.getOrderType() && 0 == ORDER_TYPE.SHOP_GOODS - orderInfo.getOrderType()))
                || (0 != ORDER_STATUS.PAYED - orderInfo.getOrderStatus() && ORDER_STATUS.POSTMAN_REFUSED != orderInfo.getOrderStatus() && (null != orderInfo.getOrderType() && (0 == ORDER_TYPE.PERSON_TRANSPORT - orderInfo.getOrderType() || 0 == ORDER_TYPE.PAO_TUI - orderInfo.getOrderType() || 0 == ORDER_TYPE.DAI_GOU - orderInfo.getOrderType() || 0 == ORDER_TYPE.BANG_BAN - orderInfo.getOrderType() || 0 == ORDER_TYPE.HUO_YUN - orderInfo.getOrderType())))
                || (0 != ORDER_STATUS.SUBMIT - orderInfo.getOrderStatus() && (null != orderInfo.getOrderType() && 0 == ORDER_TYPE.SERVICE_LOCK - orderInfo.getOrderType()))
        ) {
            //配送员是否可以在商家接单前接单
            if (null != SYS_SETTINGS.POSTMAN_GARB_ORDER_BEFORE_SHOP && 0 == 1 - SYS_SETTINGS.POSTMAN_GARB_ORDER_BEFORE_SHOP
                    && 0 == ORDER_STATUS.PAYED - orderInfo.getOrderStatus()
                    && null != orderInfo.getOrderType() && 0 == ORDER_TYPE.SHOP_GOODS - orderInfo.getOrderType()) {
                oStatus = ORDER_STATUS.POSTMAN_SURE_BEFORE_SHOP;
            } else {
                PostmanGrabMemory.getInstance().removeGrab(orderNo);
                //店铺接单后才可以抢单
                return AjaxResult.errorResult("抢单失败，请稍后再试2");
            }
        }

        //是否已抢过
        if (PostmanGrabMemory.getInstance().hasGrabThisOrder(user.getUsername(), orderNo)) {
            PostmanGrabMemory.getInstance().removeGrab(orderNo);
            return AjaxResult.errorResult("你已经抢过该订单，请耐心等待");
        }


        //判断当前订单是否被其他人抢过
        if (PostmanGrabMemory.getInstance().hasGrab(orderNo)) {
            PostmanGrabMemory.getInstance().removeGrab(orderNo);
            return AjaxResult.errorResult("该订单已被其他配送员抢了");
        }

        long time = DateUtils.getCurrTime();
        //将抢单信息加入到缓存
        OrderGrabInfo orderGrabInfo = new OrderGrabInfo(user.getUsername(), user.getName(), time, orderNo, orderInfo.getShopCity());
        PostmanGrabMemory.getInstance().grabOrder(orderGrabInfo);

        // 如果有二级骑手的话  订单验证码可能已经被生成好了 所以在这里进行判断一下
        //直接生成配送验证码，去提货
        //生成取货验证码
        String verifyCode = orderInfo.getVerifyCode();
        if (ValidateUtil.isNull(verifyCode)) {
            verifyCode = OrderMan.getVerifyCode();
        }
        if (ValidateUtil.isNull(verifyCode)) {
            PostmanGrabMemory.getInstance().removeGrab(orderNo);
            return AjaxResult.errorResult("生成验证码失败，请稍后再试");
        }

        boolean hasPostCompany = false;
        if (companyId != null && SYS_SETTINGS.THIRD_PARTY_COMPANY != null && SYS_SETTINGS.THIRD_PARTY_COMPANY == 1) {
            if (StringUtils.isNotEmpty(orderInfo.getCanGrabCompanyIds())) {
                Set<Long> set = CommonUtils.splitToSet(orderInfo.getCanGrabCompanyIds(), Long.class);
                if (set != null && !set.isEmpty() && set.contains(companyId)) {
                    PostCompanyInfo info = PostCompanyMemory.getInstance().getById(companyId);
                    if (info == null) {
                        PostmanGrabMemory.getInstance().removeGrab(orderNo);
                        return AjaxResult.errorResult("未获取到公司信息");
                    }
                    hasPostCompany = true;
                } else {
                    PostmanGrabMemory.getInstance().removeGrab(orderNo);
                    return AjaxResult.errorResult("未匹配到您的公司");
                }
            }
        }

        String postmanPhone = user.getTelPhone();
        if (ValidateUtil.isNull(postmanPhone)) {
            postmanPhone = user.getUsername();
        }
        String poto = user.getSignPhoto();
        if (OrderMan.isMultipleParentOrder(orderNo)) {
            ResultInfo resultInfo = OrderMan.postmanSureMultipleOrder(orderInfo, companyId, orderNo, oStatus, "",
                    user, user.getUsername());
//            ResultInfo resultInfo = OrderMan.postmanSureMultipleOrder(orderInfo, companyId, orderNo, oStatus, user);
            if (resultInfo == null) {
                PostmanGrabMemory.getInstance().removeGrab(orderNo);
                return AjaxResult.errorResult("抢单失败");
            }
            if (!resultInfo.isSuccess()) {
                PostmanGrabMemory.getInstance().removeGrab(orderNo);
                return AjaxResult.errorResult(resultInfo.getError());
            }


            Connection conn = null;
            try {
                conn = UserDaoSql.getInstance().getConnection();
                conn.setAutoCommit(false);
            } catch (SQLException e) {
                e.printStackTrace();
            }
            boolean isUpdateOrderPayInfo = false;
            try {
                conn.commit();
            } catch (Exception e) {
                PostmanGrabMemory.getInstance().removeGrab(user.getUsername(), orderInfo.getOrderNo());
                UserDaoSql.getInstance().rollback(conn);
                e.printStackTrace();
                return AjaxResult.errorResult(e.getMessage());
            } finally {
                UserDaoSql.getInstance().close(conn);
            }
            // 分成缓存
            if (isUpdateOrderPayInfo) {
                OrderPayMemory.getInstance().modify(orderNo);
                try {
                    JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.ORDER_PAY_MODIFY).setStr01(orderNo);
                    JmsSender.setTopicSender(notify);
                } catch (Exception e) {
                }
            }


            PostmanGrabMemory.getInstance().removeGrab(orderNo);
            deliveryOrderTask.sendNotify(orderNo);
            return AjaxResult.successResult(); // 抢单成功
        }
//        boolean hasPostCompany = false;
//        if (companyId != null && SYS_SETTINGS.THIRD_PARTY_COMPANY != null && SYS_SETTINGS.THIRD_PARTY_COMPANY == 1) {
//            if (StringUtils.isNotEmpty(orderInfo.getCanGrabCompanyIds())) {
//                Set<Long> set = CommonUtils.splitToSet(orderInfo.getCanGrabCompanyIds(), Long.class);
//                if (set != null && !set.isEmpty() && set.contains(companyId)) {
//                    PostCompanyInfo info = PostCompanyMemory.getInstance().getById(companyId);
//                    if (info == null) {
//                        PostmanGrabMemory.getInstance().removeGrab(orderNo);
//                        return AjaxResult.errorResult("未获取到公司信息");
//                    }
//                    hasPostCompany = true;
//                } else {
//                    PostmanGrabMemory.getInstance().removeGrab(orderNo);
//                    return AjaxResult.errorResult("未匹配到您的公司");
//                }
//            }
//        }


        StringBuilder sb = new StringBuilder();
        sb.append("update ").append(PojoTables.OrderInfo).append(" set orderStatus = ").append(oStatus)
                .append(",verifyCode='").append(verifyCode).append("',updateUser='").append(user.getUsername()).append("'");
        if (hasPostCompany) {
            sb.append(",grabCompanyId=").append(companyId);

            // 有了配送公司  然后还有分成
        }
        sb.append(",postmanUsername='")
                .append(user.getUsername()).append("',postmanName='").append(user.getName()).append("',postmanPhone='").append(postmanPhone)
                .append("',postmanImageUrl='").append(poto).append("',postmanSureTime=").append(time).append(" where delFlag=0 and orderNo = '").append(orderNo).append("'");
        Connection conn = null;
        try {
            conn = UserDaoSql.getInstance().getConnection();
            conn.setAutoCommit(false);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        OrderStatus orderStatus = new OrderStatus(orderNo, oStatus, user.getUsername(), time);
        boolean isUpdateOrderPayInfo = false;
        try {
            UserDaoSql.getInstance().saveObj(PojoTables.OrderStatus, orderStatus, conn);
            UserDaoSql.getInstance().executeBySql(sb.toString(), conn);

            conn.commit();
        } catch (Exception e) {
            PostmanGrabMemory.getInstance().removeGrab(user.getUsername(), orderInfo.getOrderNo());
            UserDaoSql.getInstance().rollback(conn);
            e.printStackTrace();
            return AjaxResult.errorResult(e.getMessage());
        } finally {
            UserDaoSql.getInstance().close(conn);
        }
        //订单状态缓存
        OrderStatusMemory.getInstance().addStatus(orderNo);
        //修改缓存
        OrderInfoMemory.getInstance().modifyStatus(orderNo);
        // 分成缓存
        if (isUpdateOrderPayInfo) {
            OrderPayMemory.getInstance().modify(orderNo);
            try {
                JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.ORDER_PAY_MODIFY).setStr01(orderNo);
                JmsSender.setTopicSender(notify);
            } catch (Exception e) {
            }
        }
        if (null != orderInfo.getOrderType() && 0 != ORDER_TYPE.SERVICE_LOCK - orderInfo.getOrderType()) {
            //发送一条订单通知
//            Notice.publishOrderNotice(orderInfo.getUsername(), "订单信息", "您的订单（订单编号：" + orderNo + "），已有配送员抢单了，请耐心等待");
//            //极光推送
//            JPushMessage jPushMessage = new JPushMessage(orderInfo.getUsername(), "订单信息", "您的订单（订单编号：" + orderNo + "），已有配送员抢单了，请耐心等待");
//            jPushMessage.setPushUserType(JPushMessage.USER);//推给用户
//            JPushTask.jPushMessageList.add(jPushMessage);

            Notice.publishNotice2Person(sysAppKey, orderInfo.getUsername(), JPushMessage.USER, NoticeType.order, "订单信息", "您的订单（订单编号：" + orderNo + "），已有配送员抢单了，请耐心等待", orderNo);
        }


        //开锁工单 修改工单订单状态
        if (null != orderInfo.getOrderType() && 0 == ORDER_TYPE.SERVICE_LOCK - orderInfo.getOrderType()) {
            StringBuffer sbPre = new StringBuffer();
            sbPre.append("update ").append(PojoTables.ORDER_INFO_PRE).append(" set orderStatus = ").append(oStatus)
                    .append(",verifyCode='").append(verifyCode).append("',updateUser='").append(user.getUsername()).append("',postmanUsername='")
                    .append(user.getUsername()).append("',postmanName='").append(user.getName()).append("',postmanPhone='").append(postmanPhone)
                    .append("',postmanImageUrl='").append(poto).append("',postmanSureTime=").append(time).append(" where delFlag=0 and orderNo = '").append(orderNo).append("'");
            try {
                UserDaoSql.getInstance().executeBySql(sbPre.toString());
            } catch (SQLException e) {
                e.printStackTrace();
                PostmanGrabMemory.getInstance().removeGrab(orderNo);
                return AjaxResult.errorResult("操作失败，请稍后重试");
            }
            OrderInfoPreMemory.getInstance().modifyStatus(orderNo);


            //发送短信
//            SMSInfo smsInfo = new SMSInfo(orderInfo.getTelephone(), null,
//                    null, DUBBO_SMS_TYPE.OTHER,
//                    SYS_CONFIG_SMS.POSTMAN_ORDER_GRAB);
//            SMSThreadMap.smsCodeSet.add(smsInfo);

            JYSmsSeverBusiness.sendSMS(sysAppKey, orderInfo.getTelephone(), SMS_TYPE.POSTMAN_ORDER_GRAB);

            //绑定小号
            MixComTelTask.telMap.put(orderNo, orderNo);
        }


        //跑腿订单 更新跑腿订单信息里的状态
        if (null != orderInfo.getOrderType() && (
                0 == ORDER_TYPE.PAO_TUI - orderInfo.getOrderType()
                        || 0 == ORDER_TYPE.DAI_GOU - orderInfo.getOrderType()
                        || 0 == ORDER_TYPE.BANG_BAN - orderInfo.getOrderType()
                        || 0 == ORDER_TYPE.PERSON_TRANSPORT - orderInfo.getOrderType()
                        || 0 == ORDER_TYPE.HUO_YUN - orderInfo.getOrderType())
        ) {//跑腿订单
            StringBuilder sbOther = new StringBuilder();
            sbOther.append("update ").append(PojoTables.OTHER_ORDER_INFO).append(" set  orderStatus=").append(oStatus).append(",updateUser='")
                    .append(user.getUsername()).append("' where delFlag =0 and  orderNo = '").append(orderNo).append("'");
            try {
                UserDaoSql.getInstance().executeBySql(sbOther.toString());
            } catch (SQLException e) {
                e.printStackTrace();
                PostmanGrabMemory.getInstance().removeGrab(orderNo);
                return AjaxResult.errorResult("更新订单状态失败，请稍后再试");
            }
            //缓存修改
            OtherOrderMemory.getInstance().addOrModify(orderNo);
        }

        PostmanGrabMemory.getInstance().removeGrab(orderNo);
        deliveryOrderTask.sendNotify(orderNo);
        return AjaxResult.successResult(verifyCode);
    }

    //配送员接单
    @RequestMapping(method = RequestMethod.POST, value = "/postman/order/sure")
    @ResponseBody
    public String order_postman_sure(String token, String sysAppKey, String orderNo) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        CityPostman postman = CityPostmanMemory.getInstance().getPostman(user.getUsername());
        if (null == postman) {
            return AjaxResult.errorResult("未查询到您的信息，无法操作");
        }
        //0 锁定  1未锁定
        if (null != postman.getIsLock() && 0 == 1 - postman.getIsLock()) {
            return AjaxResult.errorResult("您已被锁定，无法接单");
        }
        if (ValidateUtil.isNotAbsInteger(postman.getIsWork())) {
            return AjaxResult.errorResult("您无法接单，请先上班");
        }
        if (0 == postman.getIsWork()) {
            return AjaxResult.errorResult("请先上班");
        }
        if (null != SYS_SETTINGS.POSTMAN_MUST_VERIFY && 0 == 1 - SYS_SETTINGS.POSTMAN_MUST_VERIFY
                && (null == postman.getIsVerify() || 0 != 1 - postman.getIsVerify())) {
            return AjaxResult.errorResult("您尚未通过认证，请先去认证");
        }
        if (null != SYS_SETTINGS.POSTMAN_MUST_VERIFY_FACE && 0 == 1 - SYS_SETTINGS.POSTMAN_MUST_VERIFY_FACE) {
            if (null != user.getIsCert() && 0 == 1 - user.getIsCert()) {
                //已认证
            } else {
                return AjaxResult.errorResult("未通过实名认证，请先去认证");
            }
        }

        if (ValidateUtil.isNull(orderNo)) {
            return AjaxResult.errorResult("请选择订单");
        }

        OrderInfo orderInfo = OrderInfoMemory.getInstance().getOrderInfo(orderNo);
        if (null == orderInfo) {
            return AjaxResult.errorResult("该订单不存在");
        }


        if (ORDER_STATUS.POSTMAN_ZHIDING != orderInfo.getOrderStatus()) {
            return AjaxResult.errorResult("该状态下不允许此操作");
        }

        //判断订单状态是否可以操作
        if (ORDER_STATUS.OVER == orderInfo.getOrderStatus()
                || ORDER_STATUS.CANCEL == orderInfo.getOrderStatus()
                || ORDER_STATUS.SUBMIT == orderInfo.getOrderStatus()
                || ORDER_STATUS.PAYED_CANCEL == orderInfo.getOrderStatus()
                || ORDER_STATUS.SHOP_FINISH == orderInfo.getOrderStatus()
                || ORDER_STATUS.POSTMAN_SURE == orderInfo.getOrderStatus()
                || ORDER_STATUS.POSTMAN_FINISH == orderInfo.getOrderStatus()
                || ORDER_STATUS.POSTMAN_REFUSED == orderInfo.getOrderStatus()
                || ORDER_STATUS.SHOP_REFUSED == orderInfo.getOrderStatus()) {
            return AjaxResult.errorResult("该状态不允许操作");
        }

        //生成取货验证码
        String verifyCode = OrderMan.getVerifyCode();
        if (ValidateUtil.isNull(verifyCode)) {
            return AjaxResult.errorResult("生成验证码失败，请稍后再试");
        }


        Long time = DateUtils.getCurrTime();
        //修改订单状态为配送员已接单
        //修改数据库
        StringBuilder sb = new StringBuilder();
        sb.append("update ").append(PojoTables.OrderInfo).append(" set orderStatus = ").append(ORDER_STATUS.POSTMAN_SURE)
                .append(",verifyCode='").append(verifyCode).append("',updateUser='").append(user.getUsername()).append("',postmanSureTime=").append(time)
                .append("  where delFlag=0 and orderNo = '").append(orderNo).append("'");
        OrderStatus orderStatus = new OrderStatus(orderNo, ORDER_STATUS.POSTMAN_SURE, user.getUsername(), time);
        try {
            UserDaoSql.getInstance().insertObj(PojoTables.OrderStatus, orderStatus);
            UserDaoSql.getInstance().executeBySql(sb.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("操作失败，请稍后重试");
        }

        //订单状态缓存
        OrderStatusMemory.getInstance().addStatus(orderNo);
        //修改缓存
        OrderInfoMemory.getInstance().modifyStatus(orderNo);

        //发送一条订单通知
//        Notice.publishOrderNotice(orderInfo.getUsername(), "订单信息", "您的订单（订单编号：" + orderNo + "），配送员已接单，请耐心等待");
//        //极光推送
//        JPushMessage jPushMessage = new JPushMessage(orderInfo.getUsername(), "订单信息", "您的订单（订单编号：" + orderNo + "），配送员已接单，请耐心等待");
//        jPushMessage.setPushUserType(JPushMessage.USER);//推给用户
//        JPushTask.jPushMessageList.add(jPushMessage);

        Notice.publishNotice2Person(sysAppKey, orderInfo.getUsername(), JPushMessage.USER, NoticeType.order, "订单信息", "您的订单（订单编号：" + orderNo + "），配送员已接单，请耐心等待", orderNo);

        //跑腿订单 更新跑腿订单信息里的状态
//        if (0 == -2 - orderInfo.getShopId()) {
        if (null != orderInfo.getOrderType() && (
                0 == ORDER_TYPE.PAO_TUI - orderInfo.getOrderType()
                        || 0 == ORDER_TYPE.DAI_GOU - orderInfo.getOrderType()
                        || 0 == ORDER_TYPE.PERSON_TRANSPORT - orderInfo.getOrderType()
                        || 0 == ORDER_TYPE.BANG_BAN - orderInfo.getOrderType()
                        || 0 == ORDER_TYPE.HUO_YUN - orderInfo.getOrderType())
        ) {//跑腿订单
            StringBuilder sbOther = new StringBuilder();
            sbOther.append("update ").append(PojoTables.OTHER_ORDER_INFO).append(" set  orderStatus=").append(ORDER_STATUS.POSTMAN_SURE).append(",updateUser='")
                    .append(user.getUsername()).append("' where delFlag =0 and  orderNo = '").append(orderNo).append("'");
            try {
                UserDaoSql.getInstance().executeBySql(sbOther.toString());
            } catch (SQLException e) {
                e.printStackTrace();
                return AjaxResult.errorResult("更新订单状态失败，请稍后再试");
            }
            //缓存修改
            OtherOrderMemory.getInstance().addOrModify(orderNo);
        }

        deliveryOrderTask.sendNotify(orderNo);
        return AjaxResult.successResult();
    }

    //配送员拒绝接单
    @RequestMapping(method = RequestMethod.POST, value = "/postman/order/refuse")
    @ResponseBody
    public String order_postman_refuse(String token, String orderNo, String refuseReason) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        if (ValidateUtil.isNull(orderNo)) {
            return AjaxResult.errorResult("请选择订单");
        }

        OrderInfo orderInfo = OrderInfoMemory.getInstance().getOrderInfo(orderNo);
        if (null == orderInfo) {
            return AjaxResult.errorResult("该订单不存在");
        }
        //判断订单状态是否可以操作
        if (ORDER_STATUS.OVER == orderInfo.getOrderStatus()
                || ORDER_STATUS.CANCEL == orderInfo.getOrderStatus()
                || ORDER_STATUS.SUBMIT == orderInfo.getOrderStatus()
                || ORDER_STATUS.PAYED_CANCEL == orderInfo.getOrderStatus()
                || ORDER_STATUS.SHOP_FINISH == orderInfo.getOrderStatus()
                || ORDER_STATUS.POSTMAN_SURE == orderInfo.getOrderStatus()
                || ORDER_STATUS.POSTMAN_FINISH == orderInfo.getOrderStatus()
                || ORDER_STATUS.POSTMAN_REFUSED == orderInfo.getOrderStatus()
                || ORDER_STATUS.SHOP_REFUSED == orderInfo.getOrderStatus()) {
            return AjaxResult.errorResult("该状态不允许操作");
        }

        Long time = DateUtils.getCurrTime();
        //修改订单状态为配送员已接单
        //修改数据库
        StringBuilder sb = new StringBuilder();
        sb.append("update ").append(PojoTables.OrderInfo).append(" set orderStatus = ").append(ORDER_STATUS.POSTMAN_REFUSED)
                .append(",postManUsername='',postmanName='',postmanPhone='',postmanImageUrl=''")
                .append(",postFailReason='").append(refuseReason).append("'")
                .append(",updateUser='").append(user.getUsername()).append("',postmanFinishTime =").append(time)
                .append("  where delFlag=0 and orderNo = '").append(orderNo).append("'");

        OrderStatus orderStatus = new OrderStatus(orderNo, ORDER_STATUS.POSTMAN_REFUSED, user.getUsername(), time);
        if (ValidateUtil.isNotNull(refuseReason) && refuseReason.length() > 100) {
            refuseReason.substring(0, 90);
        }
        orderStatus.setNote(refuseReason);//拒绝接单原因
        try {
            UserDaoSql.getInstance().insertObj(PojoTables.OrderStatus, orderStatus);
            UserDaoSql.getInstance().executeBySql(sb.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("操作失败，请稍后重试");
        }

        // 清除已经抢单的配送员
        System.out.println("postmanUsername--->" + orderInfo.getPostManUsername());
        OrderInfoMemory.getInstance().removePostmanOrderInfo(orderInfo.getPostManUsername(), orderNo);
        //修改订单状态缓存
        OrderStatusMemory.getInstance().addStatus(orderNo);
        //修改缓存
        // OrderInfoMemory.getInstance().modifyStatus(orderNo);
        OrderInfoMemory.getInstance().paidModifyStatus(orderNo);


        //跑腿订单 更新跑腿订单信息里的状态
//        if (0 == -2 - orderInfo.getShopId()) {
        if (null != orderInfo.getOrderType() && (
                0 == ORDER_TYPE.PAO_TUI - orderInfo.getOrderType()
                        || 0 == ORDER_TYPE.DAI_GOU - orderInfo.getOrderType()
                        || 0 == ORDER_TYPE.BANG_BAN - orderInfo.getOrderType()
                        || 0 == ORDER_TYPE.PERSON_TRANSPORT - orderInfo.getOrderType()
                        || 0 == ORDER_TYPE.HUO_YUN - orderInfo.getOrderType())
        ) {//跑腿订单
            StringBuilder sbOther = new StringBuilder();
            sbOther.append("update ").append(PojoTables.OTHER_ORDER_INFO).append(" set  orderStatus=").append(ORDER_STATUS.POSTMAN_REFUSED).append(",updateUser='")
                    .append(user.getUsername()).append("' where delFlag =0 and  orderNo = '").append(orderNo).append("'");
            try {
                UserDaoSql.getInstance().executeBySql(sbOther.toString());
            } catch (SQLException e) {
                e.printStackTrace();
                return AjaxResult.errorResult("更新订单状态失败，请稍后再试");
            }
            //缓存修改
            OtherOrderMemory.getInstance().addOrModify(orderNo);
        }
        // 移除已抢订单 缓存
        PostmanGrabMemory.getInstance().removeGrab(orderInfo.getPostManUsername(), orderInfo.getOrderNo());
        PostmanGrabMemory.getInstance().removeGrab(orderInfo.getOrderNo());
        deliveryOrderTask.sendNotify(orderNo);
        return AjaxResult.successResult();
    }

    //配送员标记为已到店
    @RequestMapping(method = RequestMethod.POST, value = {"/order/postman/arrive/shop", "/order/postman/arrived"})
    @ResponseBody
    public String order_postman_arrive_shop(String token, String orderNo) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        OrderInfo orderInfo = OrderInfoMemory.getInstance().getOrderInfo(orderNo);
        if (null == orderInfo) {
            return AjaxResult.errorResult("该订单不存在");
        }

        //该订单是否已经转给别人
        if (ValidateUtil.isNotNull(orderInfo.getChangePostman())) {
            return AjaxResult.errorResult("您已发起转单请求，请等待对方应答");
        }

        if (!user.getUsername().equalsIgnoreCase(orderInfo.getPostManUsername())) {
            return AjaxResult.errorResult("该订单不是您的，无法操作");
        }

        if (null != SYS_SETTINGS.POSTMAN_MUST_DEPOSIT && 0 == 1 - SYS_SETTINGS.POSTMAN_MUST_DEPOSIT) {
            // 必须缴纳
            //验证押金金额是否满足
            UserWallet userWallet = UserWalletMemory.getInstance().getWallet(user.getUsername());
            if (null == userWallet) {
                return AjaxResult.errorResult("您还未缴纳押金，请先缴纳押金");
            }
            if (null == userWallet.getDepositMoney() || userWallet.getDepositMoney() <= 0) {
                return AjaxResult.errorResult("您还未缴纳押金，请先缴纳押金！");
            }
            //必须缴纳的押金金额
            Double money = SysConfigDepositMemory.getInstance().getByType(UserType.POSTMAN);
            if (null == money) {
                money = 0d;
            }

            if (JYMathDoubleUtils.sub(userWallet.getDepositMoney(), money) < 0) {
                return AjaxResult.errorResult("您缴纳的押金不足，请先缴纳押金");
            }
        }

        int status = orderInfo.getOrderStatus();
        if (status == ORDER_STATUS.CANCEL
                || status == ORDER_STATUS.CANCEL_BY_SYSTEM
                || status == ORDER_STATUS.PAYED_CANCEL
                || status == ORDER_STATUS.OVER
                || status == ORDER_STATUS.SHOP_FINISH
                || status == ORDER_STATUS.SHOP_REFUSED
                || status == ORDER_STATUS.SHOP_PUSH_GOODS
                || status == ORDER_STATUS.POSTMAN_PULL_GOODS
                || status == ORDER_STATUS.POSTMAN_CANT_FINISH
                || status == ORDER_STATUS.POSTMAN_DAODIAN
                || status == ORDER_STATUS.POSTMAN_FINISH
                || status == ORDER_STATUS.POSTMAN_REFUSED
                || status == ORDER_STATUS.PEISONG) {
            return AjaxResult.errorResult("当前订单状态下不允许操作");
        }

        String postmanTime = ",postmanArrShopTime=" + DateUtils.getCurrTime();
        // 如果是聚合订单。。。。
        if (OrderMan.isMultipleSonOrder(orderNo)) {
            // 首先设置子订单为到店状态 也设置父订单为到店状态
            try {
                OrderMan.postmanArriveShopMultipleOrder(user.getUsername(), postmanTime, orderInfo);
            } catch (Exception e) {
                e.printStackTrace();
                return AjaxResult.errorResult(e.getMessage());
            }
            return AjaxResult.successResult();
        }
        if (OrderMan.isMultipleParentOrder(orderInfo)) {
            // 聚合订单的话
            try {
                OrderMan.modifyOrderStatusMultipleOrder(user.getUsername(), orderNo, ORDER_STATUS.POSTMAN_DAODIAN, postmanTime, "");
            } catch (Exception e) {
                e.printStackTrace();
                return AjaxResult.errorResult(e.getMessage());
            }
            deliveryOrderTask.sendNotify(orderNo);
            return AjaxResult.successResult();
        }
        Integer orderStatus = ORDER_STATUS.POSTMAN_DAODIAN;
        if (orderInfo.getOrderType() != null && orderInfo.getOrderType() == ORDER_TYPE.PERSON_TRANSPORT) {
            orderStatus = ORDER_STATUS.POSTMAN_ARRIVED;
        }

        // 正常订单
//        if (!OrderMan.modifyOrderStatus(user.getUsername(), orderNo, ORDER_STATUS.POSTMAN_DAODIAN, postmanTime)) {
        if (!OrderMan.modifyOrderStatus(user.getUsername(), orderNo, orderStatus, postmanTime)) {
            return AjaxResult.errorResult("操作失败，请稍后再试");
        }

        //跑腿订单 更新跑腿订单信息里的状态
//        if (0 == -2 - orderInfo.getShopId()) {
        if (SYS_SETTINGS.CUSTOM_SYSTEM_TYPE != 1) { // 一乙项目排除在外
            if (null != orderInfo.getOrderType() && (
                    0 == ORDER_TYPE.PAO_TUI - orderInfo.getOrderType()
                            || 0 == ORDER_TYPE.DAI_GOU - orderInfo.getOrderType()
                            || 0 == ORDER_TYPE.BANG_BAN - orderInfo.getOrderType()
                            || 0 == ORDER_TYPE.PERSON_TRANSPORT - orderInfo.getOrderType()
                            || 0 == ORDER_TYPE.HUO_YUN - orderInfo.getOrderType())
            ) { //跑腿订单
                StringBuilder sbOther = new StringBuilder();
//                sbOther.append("update ").append(PojoTables.OTHER_ORDER_INFO).append(" set  orderStatus=").append(ORDER_STATUS.POSTMAN_DAODIAN).append(",updateUser='")
                sbOther.append("update ").append(PojoTables.OTHER_ORDER_INFO).append(" set  orderStatus=").append(orderStatus).append(",updateUser='")
                        .append(user.getUsername()).append("' where delFlag =0 and  orderNo = '").append(orderNo).append("'");
                try {
                    UserDaoSql.getInstance().executeBySql(sbOther.toString());
                } catch (SQLException e) {
                    e.printStackTrace();
                    return AjaxResult.errorResult("更新订单状态失败，请稍后再试");
                }
                //缓存修改
                OtherOrderMemory.getInstance().addOrModify(orderNo);
            }
            //开锁工单 开始服务
            OrderMan.modifyPreOrderStatus(user.getUsername(), orderNo, orderStatus, postmanTime, null);
        }
        deliveryOrderTask.sendNotify(orderNo);
        return AjaxResult.successResult();
    }

    //配送员标记为已取货
    @RequestMapping(method = RequestMethod.POST, value = {"/order/postman/pull", "/order/postman/receiving"})
    @ResponseBody
    public String order_postman_pull(String token, String orderNo) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        OrderInfo orderInfo = OrderInfoMemory.getInstance().getOrderInfo(orderNo);
        if (null == orderInfo) {
            return AjaxResult.errorResult("该订单不存在");
        }

        //该订单是否已经转给别人
        if (ValidateUtil.isNotNull(orderInfo.getChangePostman())) {
            return AjaxResult.errorResult("您已发起转单请求，请等待对方应答");
        }


        if (null != SYS_SETTINGS.POSTMAN_MUST_DEPOSIT && 0 == 1 - SYS_SETTINGS.POSTMAN_MUST_DEPOSIT) {
            // 必须缴纳
            //验证押金金额是否满足
            UserWallet userWallet = UserWalletMemory.getInstance().getWallet(user.getUsername());
            if (null == userWallet) {
                return AjaxResult.errorResult("您还未缴纳押金，请先缴纳押金");
            }
            if (null == userWallet.getDepositMoney() || userWallet.getDepositMoney() <= 0) {
                return AjaxResult.errorResult("您还未缴纳押金，请先缴纳押金！");
            }
            //必须缴纳的押金金额
            Double money = SysConfigDepositMemory.getInstance().getByType(UserType.POSTMAN);
            if (null == money) {
                money = 0d;
            }

            if (JYMathDoubleUtils.sub(userWallet.getDepositMoney(), money) < 0) {
                return AjaxResult.errorResult("您缴纳的押金不足，请先缴纳押金");
            }
        }

        // todo zhuwx
      /*  // 外卖订单，商家是否已经接单
        if (null != SYS_SETTINGS.POSTMAN_GARB_ORDER_BEFORE_SHOP && 0 == 1 - SYS_SETTINGS.POSTMAN_GARB_ORDER_BEFORE_SHOP && null != orderInfo.getOrderType() && 0 == ORDER_TYPE.SHOP_GOODS - orderInfo.getOrderType()) {
            if (null != orderInfo.getShopSureBySys() && 0 == 1 - orderInfo.getShopSureBySys()) {
                // 管理后台为商家接单了
            } else {
                // 商家是否已接单
                if (ValidateUtil.isNotAbsLong(orderInfo.getShopSureTime())) {
                    // 获取订单状态列表
                    List<ORDER_STATUS> statusList = OrderStatusMemory.getInstance().list(orderNo);
                    if (!ValidateUtil.isAbsList(statusList)) {
                        return AjaxResult.errorResult("商家未接单无法取货");
                    }
                    boolean isShopSure = false;
                    for (int i = 0; i < statusList.size(); i++) {
                        ORDER_STATUS statusInfo = statusList.get(i);
                        if (null == statusInfo) {
                            continue;
                        }
                        if (null != statusInfo.getOrderStatus() && 0 == ORDER_STATUS.SHOP_SURE - statusInfo.getOrderStatus()) {
                            isShopSure = true;
                        }
                    }
                    if (isShopSure) {
                        // 已接单
                    } else {
                        return AjaxResult.errorResult("商家未接单，无法取货");
                    }
                }
            }

        }*/


        int status = orderInfo.getOrderStatus();
        //美羹活动订单，提货点可以确认收货
        if (SYS_SETTINGS.CUSTOM_SYSTEM_TYPE != 1 && 0 == ORDER_TYPE.SHOP_ACTIVITY - orderInfo.getOrderType()) {
            if (0 != ORDER_STATUS.SHOP_PUSH_GOODS - orderInfo.getOrderStatus()) {
                return AjaxResult.errorResult("当前订单状态下不允许操作");
            }
        } else if (status == ORDER_STATUS.CANCEL
                || status == ORDER_STATUS.OVER
                || status == ORDER_STATUS.CANCEL_BY_SYSTEM
                || status == ORDER_STATUS.PAYED_CANCEL
                || status == ORDER_STATUS.SHOP_REFUSED
//                || status == ORDER_STATUS.SHOP_PUSH_GOODS // cancel by yantk,创业商圈订单，商家点了发货后，骑手无法点击取货，进行不下去
                || status == ORDER_STATUS.POSTMAN_PULL_GOODS
                || status == ORDER_STATUS.PEISONG) {
            return AjaxResult.errorResult("当前订单状态下不允许操作");
        }

        //美羹活动订单需要特殊处理配送员信息
        if (SYS_SETTINGS.CUSTOM_SYSTEM_TYPE != 1 && 0 == ORDER_TYPE.SHOP_ACTIVITY - orderInfo.getOrderType()) {
            String postmanPhone = user.getTelPhone();
            if (ValidateUtil.isNull(postmanPhone)) {
                postmanPhone = user.getUsername();
            }
            String poto = user.getSignPhoto();
            if (ValidateUtil.isNotNull(poto) && ValidateUtil.isNetUrl(poto)) {
                poto = poto.replace(SYS_CONFIG_PATH.IMAGE_BASE_URL, "");
            }

            StringBuilder sb = new StringBuilder();
            sb.append("update ").append(PojoTables.OrderInfo).append(" set updateUser='").append(user.getUsername()).append("',postmanUsername='")
                    .append(user.getUsername()).append("',postmanName='").append(user.getName()).append("',postmanPhone='").append(postmanPhone)
                    .append("',postmanImageUrl='").append(poto).append("' where delFlag=0 and orderNo = '").append(orderNo).append("'");
            try {
                UserDaoSql.getInstance().executeBySql(sb.toString());
            } catch (SQLException e) {
                e.printStackTrace();
                return AjaxResult.errorResult("操作失败，请稍后重试");
            }
            //修改缓存
            OrderInfoMemory.getInstance().modifyStatus(orderNo);

            orderInfo = OrderInfoMemory.getInstance().getOrderInfo(orderNo);
        }


        if (!user.getUsername().equalsIgnoreCase(orderInfo.getPostManUsername())) {
            return AjaxResult.errorResult("该订单不是您的，无法操作");
        }
        String postmanTime = ",postmanPullTime=" + DateUtils.getCurrTime();
        // 如果是聚合订单。。。。
        if (OrderMan.isMultipleSonOrder(orderNo)) {
            try {
                OrderMan.postmanPullGoodsMultipleOrder(user.getUsername(), postmanTime, orderInfo);
            } catch (Exception e) {
                e.printStackTrace();
                return AjaxResult.errorResult("操作失败,请稍后重试");
            }
            return AjaxResult.successResult();
        }
        if (OrderMan.isMultipleParentOrder(orderInfo)) {
            // 聚合订单的话
            try {
                OrderMan.modifyOrderStatusMultipleOrder(user.getUsername(), orderNo, ORDER_STATUS.POSTMAN_PULL_GOODS, postmanTime, "");
            } catch (Exception e) {
                e.printStackTrace();
                return AjaxResult.errorResult(e.getMessage());
            }
            deliveryOrderTask.sendNotify(orderNo);
            return AjaxResult.successResult();
        }
        // 正常订单

        Integer orderStatus = ORDER_STATUS.POSTMAN_PULL_GOODS;
        if (orderInfo.getOrderType() != null && orderInfo.getOrderType() == ORDER_TYPE.PERSON_TRANSPORT) {
            orderStatus = ORDER_STATUS.POSTMAN_RECEIVING_PASSENGER;
        }
//        String postmanTime = ",postmanPullTime=" + DateUtils.getCurrTime();
//        if (!OrderMan.modifyOrderStatus(user.getUsername(), orderNo, ORDER_STATUS.POSTMAN_PULL_GOODS, postmanTime)) {
        if (!OrderMan.modifyOrderStatus(user.getUsername(), orderNo, orderStatus, postmanTime)) {
            return AjaxResult.errorResult("操作失败，请稍后再试");
        }

        OrderInfoMemory.getInstance().removeVerifyCode(orderNo, orderInfo.getVerifyCode());//配送员点击已取货，将验证码释放
        // 刷新一下缓存 将数据验证码存入
        if (SYS_SETTINGS.HAS_ORDER_SECOND_POSTMAN_VERIFY_CODE == 1) {
            OrderInfoMemory.getInstance().modifyStatus(orderNo);
        }

        //跑腿订单 更新跑腿订单信息里的状态
//        if (0 == -2 - orderInfo.getShopId()) {
        if (null != orderInfo.getOrderType() && (
                0 == ORDER_TYPE.PAO_TUI - orderInfo.getOrderType()
                        || 0 == ORDER_TYPE.DAI_GOU - orderInfo.getOrderType()
                        || 0 == ORDER_TYPE.BANG_BAN - orderInfo.getOrderType()
                        || 0 == ORDER_TYPE.PERSON_TRANSPORT - orderInfo.getOrderType()
                        || 0 == ORDER_TYPE.HUO_YUN - orderInfo.getOrderType())
        ) {//跑腿订单
            StringBuilder sbOther = new StringBuilder();
//            sbOther.append("update ").append(PojoTables.OTHER_ORDER_INFO).append(" set  orderStatus=").append(ORDER_STATUS.POSTMAN_PULL_GOODS).append(",updateUser='")
            sbOther.append("update ").append(PojoTables.OTHER_ORDER_INFO).append(" set  orderStatus=").append(orderStatus).append(",updateUser='")
                    .append(user.getUsername()).append("' where delFlag =0 and  orderNo = '").append(orderNo).append("'");
            try {
                UserDaoSql.getInstance().executeBySql(sbOther.toString());
            } catch (SQLException e) {
                e.printStackTrace();
                return AjaxResult.errorResult("更新订单状态失败，请稍后再试");
            }
            //缓存修改
            OtherOrderMemory.getInstance().addOrModify(orderNo);
        }
        deliveryOrderTask.sendNotify(orderNo);
        return AjaxResult.successResult();
    }


    //配送员确认送达  即已完成等待用户确认
    @RequestMapping(method = RequestMethod.POST, value = "/postman/order/finish")
    @ResponseBody
    public String order_postman_finish(String token, String sysAppKey,
                                       String orderNo,
                                       Double lat, Double lng, String province, String city, String county, String address,
                                       String itemsJson) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        if (ValidateUtil.isNull(orderNo)) {
            return AjaxResult.errorResult("请选择订单");
        }

        OrderInfo orderInfo = OrderInfoMemory.getInstance().getOrderInfo(orderNo);
        if (null == orderInfo) {
            return AjaxResult.errorResult("该订单不存在");
        }

        //该订单是否已经转给别人
        if (ValidateUtil.isNotNull(orderInfo.getChangePostman())) {
            return AjaxResult.errorResult("您已发起转单请求，请等待对方应答");
        }

        if (!user.getUsername().equalsIgnoreCase(orderInfo.getPostManUsername())) {
            return AjaxResult.errorResult("该订单不是您的，无法操作");
        }

        if (null != SYS_SETTINGS.POSTMAN_MUST_DEPOSIT && 0 == 1 - SYS_SETTINGS.POSTMAN_MUST_DEPOSIT) {
            // 必须缴纳
            //验证押金金额是否满足
            UserWallet userWallet = UserWalletMemory.getInstance().getWallet(user.getUsername());
            if (null == userWallet) {
                return AjaxResult.errorResult("您还未缴纳押金，请先缴纳押金");
            }
            if (null == userWallet.getDepositMoney() || userWallet.getDepositMoney() <= 0) {
                return AjaxResult.errorResult("您还未缴纳押金，请先缴纳押金！");
            }
            //必须缴纳的押金金额
            Double money = SysConfigDepositMemory.getInstance().getByType(UserType.POSTMAN);
            if (null == money) {
                money = 0d;
            }

            if (JYMathDoubleUtils.sub(userWallet.getDepositMoney(), money) < 0) {
                return AjaxResult.errorResult("您缴纳的押金不足，请先缴纳押金");
            }
        }
        //判断订单状态是否可以操作
        if (ORDER_STATUS.OVER == orderInfo.getOrderStatus()
                || ORDER_STATUS.PAYED == orderInfo.getOrderStatus()
                || ORDER_STATUS.CANCEL == orderInfo.getOrderStatus()
                || ORDER_STATUS.SUBMIT == orderInfo.getOrderStatus()
                || ORDER_STATUS.PAYED_CANCEL == orderInfo.getOrderStatus()
                || ORDER_STATUS.SHOP_FINISH == orderInfo.getOrderStatus()
                || ORDER_STATUS.POSTMAN_SURE == orderInfo.getOrderStatus()
                || ORDER_STATUS.POSTMAN_FINISH == orderInfo.getOrderStatus()
                || ORDER_STATUS.POSTMAN_REFUSED == orderInfo.getOrderStatus()
                || ORDER_STATUS.POSTMAN_PICK_POINT == orderInfo.getOrderStatus() // 送达提货点
                || ORDER_STATUS.SECONDARY_POSTMAN_PULL_GOODS == orderInfo.getOrderStatus() // 二级骑手取货了
                || ORDER_STATUS.SHOP_REFUSED == orderInfo.getOrderStatus()) {
            return AjaxResult.errorResult("该状态不允许操作");
        }

        if (null != orderInfo.getOrderType() && 0 == ORDER_TYPE.SERVICE_LOCK - orderInfo.getOrderType()) {
            if (ValidateUtil.isNull(itemsJson)) {
                return AjaxResult.errorResult("请填写服务内容");
            }
            ResultInfo fResult = finishOrder(orderNo, itemsJson, user.getUsername());
            if (null == fResult) {
                return AjaxResult.errorResult("操作失败，请稍后再试。");
            }
            if (!fResult.isSuccess()) {
                return AjaxResult.errorResult(fResult.getError());
            }
        }
        // 订单是否提前配送完成  记录
        String postmanAdvance = "";
        if (SYS_SETTINGS.IS_CHECK_ORDER_OVERTIME != null && SYS_SETTINGS.IS_CHECK_ORDER_OVERTIME == 1) {
            OrderOverTimeInfo agentOverTimeInfoByAgentId = getAgentOverTimeInfoByAgentId(orderInfo.getAgentId());
            if (agentOverTimeInfoByAgentId != null && agentOverTimeInfoByAgentId.getNotTakenOrderTime() != null && agentOverTimeInfoByAgentId.getNotTakenOrderTime() > 0) {
                if (DateUtils.getCurrTime() - orderInfo.getPostmanSureTime() < agentOverTimeInfoByAgentId.getNotTakenOrderTime() * 60 * 1000L) {
                    postmanAdvance = ",isPostmanAdvanceTime = 1,agentPostmanAdvanceTime=" + agentOverTimeInfoByAgentId.getNotTakenOrderTime();
                }
            }
        }
        Long time = DateUtils.getCurrTime();
        if (OrderMan.isMultipleSonOrder(orderInfo)) {
            return AjaxResult.errorResult("您选择的是子订单");
        }
        Integer order_status = ORDER_STATUS.POSTMAN_FINISH;
        String userFinishTimeStr = "";
        if (orderInfo.getOrderType() != null && orderInfo.getOrderType() == ORDER_TYPE.PERSON_TRANSPORT) {
            order_status = ORDER_STATUS.OVER;
            userFinishTimeStr = " ,userFinishTime = " + DateUtils.getCurrTime();
        }
        if (OrderMan.isMultipleParentOrder(orderInfo)) {
            String opTime = ",postmanFinishTime=" + time;
            try {
                OrderMan.modifyOrderStatusMultipleOrder(user.getUsername(), orderNo, ORDER_STATUS.POSTMAN_FINISH, opTime, "");
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            //修改订单状态为配送员已接单
            //修改数据库
            StringBuilder sb = new StringBuilder();
//            sb.append("update ").append(PojoTables.OrderInfo).append(" set orderStatus = ").append(ORDER_STATUS.POSTMAN_FINISH)
            sb.append("update ").append(PojoTables.OrderInfo).append(" set orderStatus = ").append(order_status)
                    .append(",updateUser='").append(user.getUsername()).append("',postmanFinishTime=").append(time).append(postmanAdvance)
                    .append(userFinishTimeStr)
                    .append(" where delFlag=0 and orderNo = '").append(orderNo).append("'");

            OrderStatus orderStatus1 = new OrderStatus(orderNo, ORDER_STATUS.POSTMAN_FINISH, user.getUsername(), time);
            OrderStatus orderStatus2 = null;
            if (orderInfo.getOrderType() != null & orderInfo.getOrderType() == ORDER_TYPE.PERSON_TRANSPORT) {
                orderStatus2 = new OrderStatus(orderNo, ORDER_STATUS.OVER, user.getUsername(), time);
            }
            try {
                UserDaoSql.getInstance().insertObj(PojoTables.OrderStatus, orderStatus1);
                if (orderStatus2 != null) {
                    UserDaoSql.getInstance().insertObj(PojoTables.OrderStatus, orderStatus2);
                }
                UserDaoSql.getInstance().executeBySql(sb.toString());
            } catch (SQLException e) {
                e.printStackTrace();
                return AjaxResult.errorResult("操作失败，请稍后重试");
            }

            //修改订单状态缓存
            OrderStatusMemory.getInstance().addStatus(orderNo);
            //修改缓存
            OrderInfoMemory.getInstance().modifyStatus(orderNo);
        }
        if (SYS_SETTINGS.CUSTOM_SYSTEM_TYPE == 1) {

        } else {
            //更新订单支付中的配送员，以备分配金额
            updateOrderPayPostman(orderNo, user.getUsername(), user.getUsername());

            // 好管家购物 自配送订单 有工人需要重新分成计算
            if (null != orderInfo.getOrderType() && 0 == ORDER_TYPE.SHOP_GOODS - orderInfo.getOrderType()) {
                if (ValidateUtil.isAbsLong(orderInfo.getShopId())) {
                    ShopInfo shopInfo = ShopMemory.getInstance().getShopById(orderInfo.getShopId());
                    if (shopInfo != null) {
                        if (ValidateUtil.isAbsInteger(shopInfo.getIsSelfPost()) && shopInfo.getIsSelfPost() - 1 == 0 && ValidateUtil.isNotNull(orderInfo.getPostManUsername())
                                && ValidateUtil.isNotNull(shopInfo.getOwnUsername()) && !shopInfo.getOwnUsername().equals(orderInfo.getPostManUsername())) {
                            // 更新分成
                            updateOrderPay(orderInfo, orderNo, shopInfo);
                        }
                    }
                }
            }
            //分成
            if (null != orderInfo.getOrderType() && 0 != ORDER_TYPE.SERVICE_LOCK - orderInfo.getOrderType()) {
                ResultInfo resultInfo = null;
                if (OrderMan.isMultipleParentOrder(orderInfo)) {
                    // 聚合订单分成
                    resultInfo = OrderPay.distributeMoneyMulti(orderInfo, orderNo, user.getUsername());
                } else {
                    resultInfo = OrderPay.distributeMoney(orderInfo, orderNo, user.getUsername());
                }
                if (null != resultInfo && !resultInfo.isSuccess()) {
                    System.out.println("完成订单，但是分成失败：" + resultInfo.getError());
                }
            }
            OverOrderThread.map.put(orderNo, orderInfo);//加入自动完成线程，超时未确认的  系统确认完成
        }


        //增加收入
//        ResultInfo resultInfo = OrderPay.postmanAddFlow(orderInfo, user.getUsername());
//        if (null != resultInfo && !resultInfo.isSuccess()) {
//            System.out.println("配送员完成订单，但是配送员分成失败：" + resultInfo.getError());
//        }


        //保存配送员确认送达位置
//        if (ValidateUtil.isAbsDouble(lat) && ValidateUtil.isAbsDouble(lng)) {
        if (ValidateUtil.isLatLng(lat, lng)) {
            OrderOtherInfo info = new OrderOtherInfo();
            info.setOrderNo(orderNo);
            info.setLat(lat);
            info.setLng(lng);
            info.setProvince(province);
            info.setCity(city);
            info.setCounty(county);
            info.setAddress(address);
            info.setCreateTime(time);
            info.setDelFlag(0);
            info.setCreateUser(user.getUsername());
            try {
                UserDaoSql.getInstance().insertObj(PojoTables.ORDER_OTHER, info);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (null != orderInfo.getOrderType() && 0 != ORDER_TYPE.SERVICE_LOCK - orderInfo.getOrderType()) {
            if (orderInfo.getOrderType() != null && orderInfo.getOrderType() == ORDER_TYPE.PERSON_TRANSPORT) {
                Notice.publishNotice2Person(sysAppKey, orderInfo.getUsername(), JPushMessage.USER, NoticeType.order, "订单信息", "您的订单（订单编号：" + orderNo + "）,已完成", orderNo);
            } else {
                Notice.publishNotice2Person(sysAppKey, orderInfo.getUsername(), JPushMessage.USER, NoticeType.order, "订单信息", "您的订单（订单编号：" + orderNo + "），配送员已确认送达，请尽快确认订单完成", orderNo);
            }
//            Notice.publishNotice2Person(sysAppKey, orderInfo.getUsername(), JPushMessage.USER, NoticeType.order, "订单信息", "您的订单（订单编号：" + orderNo + "），配送员已确认送达，请尽快确认订单完成", orderNo);
        }
        // 删除验证码
        if (ValidateUtil.isNotNull(orderInfo.getVerifyCode())) {
            OrderInfoMemory.getInstance().removeVerifyCode(orderInfo.getOrderNo(), orderInfo.getVerifyCode());
        }
        //跑腿订单 更新跑腿订单信息里的状态
        if (null != orderInfo.getOrderType() && (
                0 == ORDER_TYPE.PAO_TUI - orderInfo.getOrderType()
                        || 0 == ORDER_TYPE.DAI_GOU - orderInfo.getOrderType()
                        || 0 == ORDER_TYPE.BANG_BAN - orderInfo.getOrderType()
                        || 0 == ORDER_TYPE.PERSON_TRANSPORT - orderInfo.getOrderType()
                        || 0 == ORDER_TYPE.HUO_YUN - orderInfo.getOrderType())
        ) {//跑腿订单
            StringBuilder sbOther = new StringBuilder();
            sbOther.append("update ").append(PojoTables.OTHER_ORDER_INFO).append(" set  orderStatus=").append(order_status).append(",updateUser='")
                    .append(user.getUsername()).append("' where delFlag =0 and  orderNo = '").append(orderNo).append("'");
            try {
                UserDaoSql.getInstance().executeBySql(sbOther.toString());
            } catch (SQLException e) {
                e.printStackTrace();
                return AjaxResult.errorResult("更新订单状态失败，请稍后再试");
            }
            //缓存修改
            OtherOrderMemory.getInstance().addOrModify(orderNo);
        }
        // 线路车骑手确认送达 即订单完成
        if (orderInfo.getOrderType() != null && orderInfo.getOrderType() == ORDER_TYPE.PERSON_TRANSPORT) {
            //TODO:分销处理-订单完成
            if (null != SYS_SETTINGS.IS_OPEN_DISTRIBUTION && 0 == 1 - SYS_SETTINGS.IS_OPEN_DISTRIBUTION) {
                try {
                    String requrstStr = HttpRequest.sendPost(SYS_CONFIG_PATH.FEN_XIAO_SERVICE_URL + "/api/distribute/order/commision/finish"
                            , "orderNo=" + orderInfo.getOrderNo() + "&sysCustomer=" + SYS_CONFIG_PATH.FEN_XIAO_SERVICE_KEY);
                    DeviceCompanyContact companyContact = new Gson().fromJson(requrstStr, DeviceCompanyContact.class);
                    if (null == companyContact) {
                        System.out.println("分销失败 " + orderInfo.getOrderNo());
                    }
                    if (0 == 1 - companyContact.getStatus()) {
                        System.out.println("分销处理-订单完成 " + orderInfo.getOrderNo());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    System.out.println("分销处理失败");
                }
            }
        }
        deliveryOrderTask.sendNotify(orderNo);
        return AjaxResult.successResult();
    }

    // 获取商圈设置
    private static OrderOverTimeInfo getAgentOverTimeInfoByAgentId(Long agentId) {
        if (agentId == null) {
            return null;
        }
        OrderOverTimeInfo info = AgentOrderOverTimeMemory.getInstance().getAgentOrderOverTimeInfoByAgentId(agentId);
        if (info == null) {
            info = AgentOrderOverTimeMemory.getInstance().getPlateDefaultSetting();
        }
        return info;
    }


    //无法送达
    @RequestMapping(method = RequestMethod.POST, value = "/postman/order/cantfinish")
    @ResponseBody
    public String order_postman_canotFinish(String token, String sysAppKey, String orderNo, String reason) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        if (ValidateUtil.isNull(orderNo)) {
            return AjaxResult.errorResult("请选择订单");
        }

        OrderInfo orderInfo = OrderInfoMemory.getInstance().getOrderInfo(orderNo);
        if (null == orderInfo) {
            return AjaxResult.errorResult("该订单不存在");
        }

        //该订单是否已经转给别人
        if (ValidateUtil.isNotNull(orderInfo.getChangePostman())) {
            return AjaxResult.errorResult("您已发起转单请求，请等待对方应答");
        }

        //判断订单状态是否可以操作
        if (ORDER_STATUS.OVER == orderInfo.getOrderStatus()
                || ORDER_STATUS.CANCEL == orderInfo.getOrderStatus()
                || ORDER_STATUS.PAYED_CANCEL == orderInfo.getOrderStatus()
                || ORDER_STATUS.SHOP_FINISH == orderInfo.getOrderStatus()
                || ORDER_STATUS.POSTMAN_FINISH == orderInfo.getOrderStatus()
                || ORDER_STATUS.POSTMAN_REFUSED == orderInfo.getOrderStatus()
                || ORDER_STATUS.SHOP_REFUSED == orderInfo.getOrderStatus()) {
            return AjaxResult.errorResult("该状态不允许操作");
        }


        Long time = DateUtils.getCurrTime();
        //修改订单状态为配送员已接单
        //修改数据库
        StringBuilder sb = new StringBuilder();
        sb.append("update ").append(PojoTables.OrderInfo).append(" set orderStatus = ").append(ORDER_STATUS.POSTMAN_CANT_FINISH)
                .append(",updateUser='").append(user.getUsername()).append("',postmanFinishTime=").append(time).append(",postFailReason='").append(reason).append("'")
                .append(" where delFlag=0 and orderNo = '").append(orderNo).append("'");

        OrderStatus orderStatus = new OrderStatus(orderNo, ORDER_STATUS.POSTMAN_CANT_FINISH, user.getUsername(), time);
        if (ValidateUtil.isNotNull(reason) && reason.length() > 100) {
            reason.substring(0, 90);
        }
        orderStatus.setNote(reason);//无法送达原因
        try {
            UserDaoSql.getInstance().insertObj(PojoTables.OrderStatus, orderStatus);
            UserDaoSql.getInstance().executeBySql(sb.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("操作失败，请稍后重试");
        }

        //修改订单状态缓存
        OrderStatusMemory.getInstance().addStatus(orderNo);
        //修改缓存
        OrderInfoMemory.getInstance().modifyStatus(orderNo);

        if (null != orderInfo.getOrderType() && 0 != ORDER_TYPE.SERVICE_LOCK - orderInfo.getOrderType()) {
            //发送一条订单通知
//            Notice.publishOrderNotice(orderInfo.getUsername(), "订单信息", "您的订单（订单编号：" + orderNo + "），配送员无法送达，您可以联系客服，查询详细细信息");
//            //极光推送
//            JPushMessage jPushMessage = new JPushMessage(orderInfo.getUsername(), "订单信息", "您的订单（订单编号：" + orderNo + "），配送员无法送达，您可以联系客服，查询详细细信息");
//            jPushMessage.setPushUserType(JPushMessage.USER);//推给用户
//            JPushTask.jPushMessageList.add(jPushMessage);

            Notice.publishNotice2Person(sysAppKey, orderInfo.getUsername(), JPushMessage.USER, NoticeType.order, "订单信息", "您的订单（订单编号：" + orderNo + "），配送员无法送达，您可以联系客服，查询详细细信息");
        }

        //如果是工人发单 则需要修改原订单信息
        if (null != orderInfo.getOrderType() && 0 == ORDER_TYPE.SERVICE_LOCK - orderInfo.getOrderType()) {
            //如果是转单 则需要修改原订单信息
            OrderInfoPre preInfo = OrderInfoPreMemory.getInstance().getOrderInfo(orderNo);
            if (null != preInfo) {
                String postmanSureTime = ",postmanFinishTime=" + DateUtils.getCurrTime();
                OrderMan.modifyPreOrderStatus(user.getUsername(), orderNo, ORDER_STATUS.POSTMAN_CANT_FINISH, postmanSureTime, null);
            }

            //解绑小号
            MixComTelTask.unbindMap.put(orderNo, orderNo);
        }
        deliveryOrderTask.sendNotify(orderNo);
        return AjaxResult.successResult();
    }

    // 计算费用
    @RequestMapping(method = RequestMethod.POST, value = "/order/drive-price")
    @ResponseBody
    public String order_drive_(Double lat1, Double lng1, Double lat2, Double lng2, Integer orderType) {
        if (ValidateUtil.isNotLatLng(lat1, lng1) || ValidateUtil.isNotLatLng(lat2, lng2) || orderType == null) {
            return AjaxResult.successResult(0 + "");
        }
        Double deliveryPrice = 0.0D;
        if (null != SYS_SETTINGS.SELECT_DISTRIBUTION_FEE && 0 == 2 - SYS_SETTINGS.SELECT_DISTRIBUTION_FEE) { //配送费计算方式 1固定配送费 2 按距离（平台）计算 3按距离（店铺）
            //2 按距离（平台）计算
            //验证按距离计算的配送费是否正确
            double distance = Geohash.distance(lat1, lng1, lat2, lng2);
            OrderTypeInfo typeInfo = OrderTypeMemory.getInstance().get(orderType);
            if (typeInfo == null) {
                return AjaxResult.errorResult("未获取到订单类型信息");
            }

            Double km = JYMathDoubleUtils.div(distance, 1000);
            if (typeInfo != null) {
                if (km - typeInfo.getWithinDistance() <= 0) {
                    deliveryPrice = typeInfo.getFixedCost();
                } else {
                    Double after = JYMathDoubleUtils.sub(km, typeInfo.getWithinDistance());
                    Double round = Math.ceil(after);
                    deliveryPrice = JYMathDoubleUtils.add(typeInfo.getFixedCost(), JYMathDoubleUtils.mul(round, typeInfo.getOneKmCost()));
                }
            } else {
                System.out.println("未设置平台配送费设置");
            }
        }
        return AjaxResult.successResult(deliveryPrice + "");
    }

    // 订单退回到订大厅内
    @RequestMapping(method = RequestMethod.POST, value = "/postman/order/back")
    @ResponseBody
    public String order_postman_back(String token, String sysAppKey, String orderNo) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (ValidateUtil.isNull(orderNo)) {
            return AjaxResult.errorResult("订单编号不能为空");
        }
        OrderInfo info = OrderInfoMemory.getInstance().getOrderInfo(orderNo);
        if (info == null) {
            return AjaxResult.errorResult("未获取到订单信息");
        }
        if (ValidateUtil.isNull(info.getPostManUsername()) || !info.getPostManUsername().equals(user.getUsername())) {
            return AjaxResult.errorResult("该订单不属于您的");
        }
        CityPostman postman = CityPostmanMemory.getInstance().getPostman(user.getUsername());
        if (postman == null) {
            return AjaxResult.errorResult("未获取到配送员信息");
        }
        if (info.getOrderStatus() != ORDER_STATUS.POSTMAN_SURE
                && info.getOrderStatus() != ORDER_STATUS.SHOP_SURE
                && info.getOrderStatus() != ORDER_STATUS.POSTMAN_ARRIVED // 到达指定位置
                && info.getOrderStatus() != ORDER_STATUS.POSTMAN_SURE_BEFORE_SHOP) {
            return AjaxResult.errorResult("当前状态下不能操作");
        }
        try {
            OrderMan.postmanBackOrder(info, user, postman, true);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.errorResult(e.getMessage());
        }
//        if (ValidateUtil.isNotNull(info.getChangePostman())) {
//            return AjaxResult.errorResult("当前正在转单,无法操作");
//        }
//        CityPostman postman = CityPostmanMemory.getInstance().getPostman(user.getUsername());
//        if (postman == null) {
//            return AjaxResult.errorResult("未获取到配送员信息");
//        }
//        long time = DateUtils.getCurrTime();
//        // 时间
//        if (info.getPostmanBackOrderTime() == null || info.getPostmanBackOrderTime() == 0) {
//            if (time - info.getPostmanSureTime() > SYS_SETTINGS.POSTMAN_CAN_BACK_TIME * 60 * 1000L) {
//                return AjaxResult.errorResult("时间已经超时,您无法退回订单");
//            }
//        } else {
//            if (time - info.getPostmanSureTime() > info.getPostmanBackOrderTime() * 60 * 1000L) {
//                return AjaxResult.errorResult("您无法将订单退回订单大厅");
//            }
//        }
//        long count = 0;
//        StringBuilder countsql = new StringBuilder();
//        countsql.append("select count(*) as counts  ").append(PojoTables.ORDER_POSTMAN_BACK)
//                .append(" where username = '").append(user.getUsername()).append("' and delFlag =0  ")
//                .append(" and from_unixtime(createTime/1000,'%Y%m%d')=date_format(now(),'%Y%m%d') ");
//        try {
//            count = UserDaoSql.getInstance().getCount(countsql.toString());
//        } catch (SQLException e) {
//            e.printStackTrace();
//            return AjaxResult.errorResult("获取当前配送员转单数失败");
//        }
//        if (count > SYS_SETTINGS.POSTMAN_CAN_BACK_COUNT_PRE_DAY) {
//            return AjaxResult.errorResult("超出了今天退单次数");
//        }
//        if (info.getOrderStatus() != ORDER_STATUS.POSTMAN_SURE
//                && info.getOrderStatus() != ORDER_STATUS.SHOP_SURE
//                && info.getOrderStatus() != ORDER_STATUS.POSTMAN_SURE_BEFORE_SHOP) {
//            return AjaxResult.errorResult("当前状态下不能操作");
//        }
//        List<OrderStatus> orderStatusList = OrderStatusMemory.getInstance().list(orderNo);
//        if (orderStatusList == null) {
//            return AjaxResult.errorResult("订单异常,请联系客服");
//        }
//        int orderStatus = ORDER_STATUS.SHOP_SURE;
//        if (info.getOrderStatus() == ORDER_STATUS.SHOP_SURE) {
//
//        } else if (ORDER_STATUS.POSTMAN_SURE_BEFORE_SHOP == info.getOrderStatus()) {
////            for (OrderStatus status : orderStatusList) {
////                if (status.getOrderStatus() != ORDER_STATUS.POSTMAN_SURE_BEFORE_SHOP) {
////                    orderStatus = status.getOrderStatus();
////                }
////            }
//            orderStatus = ORDER_STATUS.PAYED;
//        } else {
//            orderStatus = ORDER_STATUS.SHOP_SURE;
//        }
//        OrderPostmanBackInfo backInfo = new OrderPostmanBackInfo();
//        // 退单生成记录
//        backInfo.setBackTime(time).setDelFlag(0).setCreateTime(time).setCreateUser(user.getUsername()).setOrderNo(orderNo)
//                .setPostmanName(user.getName()).setPostmanId(postman.getId()).setPostmanPhone(user.getTelPhone()).setPostmanImageUrl(user.getSignPhoto());
//        // 退单记录
//        StringBuilder sql = new StringBuilder();
//        sql.append("update ").append(PojoTables.OrderInfo).append(" set updateUser = '").append(user.getUsername()).append("'")
//                .append(", orderStatus = '").append(orderStatus).append("'")
//                .append(", postManUsername = '',postmanName='',postmanPhone='',postmanImageUrl='',postmanSureTime=NULL")
//                .append(", extra2 ='").append(postman.getUsername()).append("'")
//                .append(" where orderNo = '").append(orderNo).append("'").append(" and delFlag = 0");
//        try {
//            UserDaoSql.getInstance().executeBySql(sql.toString());
//            UserDaoSql.getInstance().saveObj(PojoTables.ORDER_POSTMAN_BACK, backInfo);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return AjaxResult.errorResult("操作失败,请稍后重试");
//        }
//        OrderInfoMemory.getInstance().modifyStatus(orderNo);
        return AjaxResult.successResult();
    }


    //--------------------------
    //更新配送员
    private boolean updateOrderPayPostman(String orderNo, String postman, String opUsername) {
        if (ValidateUtil.isNull(orderNo)) {
            return false;
        }
        if (ValidateUtil.isNull(postman)) {
            return false;
        }

        StringBuffer sb = new StringBuffer();
        sb.append("update ").append(PojoTables.OrderPay).append(" set postman = '").append(postman).append("',updateUser='").append(opUsername)
                .append("' where orderNo = '").append(orderNo).append("' and delFlag = 0");
        try {
            UserDaoSql.getInstance().executeBySql(sb.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }

        //更新缓存
        OrderPayMemory.getInstance().modify(orderNo);
        try {
            JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.ORDER_PAY_MODIFY).setStr01(orderNo);
            JmsSender.setTopicSender(notify);
        } catch (Exception e) {
        }

        return true;
    }


    // 好管家  由于自配送订单有配送员造成的分成问题
    private ResultInfo updateOrderPay(OrderInfo orderInfo, String orderNo, ShopInfo shopInfo) {
        if (null == orderInfo) {
            return new ResultInfo("分成出错，订单信息为空·");
        }

        //add by zhuwx 2018-9-25
        OrderPayInfo orderPayInfoR = OrderPayMemory.getInstance().get(orderNo);
        if (null != orderPayInfoR) {
            return new ResultInfo("已经分成过了");
        }

        //商品总金额
        Double totalGoodsMoney = orderInfo.getTotalGoodsMoney();//商品的金额
        //支付金额
        Double payMoney = orderInfo.getTotalPrice();//用户支付的金额
        //配送费
        Double deliveryPrice = orderInfo.getDeliveryPrice();//配送费
        Double packetPrice = orderInfo.getPacketPrice();//打包费

        // 税费
        Double taxMoney = orderInfo.getGoodsTaxMoney();

        if (null == taxMoney) {
            taxMoney = 0d;
        }
        if (null == payMoney) {
            payMoney = 0d;
        }
        if (null == deliveryPrice) {
            deliveryPrice = 0d;
        }
        if (null == packetPrice) {
            packetPrice = 0d;
        }
        if (ValidateUtil.isNotAbsDouble(totalGoodsMoney)) {
            if (null == deliveryPrice) {
                orderInfo.setDeliveryPrice(0d);
            }
            if (null == packetPrice) {
                orderInfo.setPacketPrice(0d);
            }
            if (ValidateUtil.isNotAbsDouble(orderInfo.getTotalMoney())) {
                if (ValidateUtil.isAbsDouble(payMoney)) {
                    orderInfo.setTotalMoney(JYMathDoubleUtils.add(JYMathDoubleUtils.add(payMoney, deliveryPrice), packetPrice));
                }
            }
            totalGoodsMoney = JYMathDoubleUtils.sub(orderInfo.getTotalMoney(), deliveryPrice);
        }

        Double shopRate = 0d;
        Double shopTotalMoney = totalGoodsMoney;//店铺实际订单金额 未分成前（商品总金额 加上应该加的配送费 减掉店铺减的金额）
        Double shopMoney = 0d;//店铺实际收入 分成后
        Double postmanRate = 0d;
        Double postmanTotalMoney = 0d;
        Double postmanMoney = 0d;

        //活动金额处理
        Double shopAwardMoney = orderInfo.getShopAwardMoney();//活动满减金额-店铺减金额
        Double platformAwardMoney = orderInfo.getPlatformAwardMoney();//活动满减金额-平台减金额

        Long sellerId = orderInfo.getShopId();
        String sellerUsername = "";


        // 是否有工人 配送员等
        boolean hasPostman = false;
        if (ValidateUtil.isNotNull(orderInfo.getPostManUsername())) {
            hasPostman = true;
        }

        //1.店铺分成
        if (null != orderInfo.getOrderType()
                && 0 != ORDER_TYPE.PAO_TUI - orderInfo.getOrderType()
                && 0 != ORDER_TYPE.DAI_GOU - orderInfo.getOrderType()
                && 0 != ORDER_TYPE.BANG_BAN - orderInfo.getOrderType()
                && 0 != ORDER_TYPE.HUO_YUN - orderInfo.getOrderType()
                && 0 != ORDER_TYPE.SERVICE_LOCK - orderInfo.getOrderType()) { //跑腿订单
            if (null != shopInfo) {
                sellerId = shopInfo.getId();
                sellerUsername = shopInfo.getOwnUsername();
                shopRate = shopInfo.getMoneyRate();//分配比例
            }

            if (null == SYS_SETTINGS.SHOP_SHARE_DELIVERY_MONEY) {
                System.out.println("未设置店铺是否分成配送费部分");
                return new ResultInfo("操作失败，请稍后再试。1");
            }
            //店铺是自配送
            if (null != shopInfo && null != shopInfo.getIsSelfPost() && 0 == 1 - shopInfo.getIsSelfPost() && !hasPostman) {
                Integer isDeliveryShare = SYS_SETTINGS.SHOP_SHARE_DELIVERY_MONEY;//店铺分成时  订单的配送费是否参与分成 1 参与
                if (0 == 1 - isDeliveryShare) { //店铺分成时  配送费参与分成
                    //配送费店铺参与分成
                    shopTotalMoney = JYMathDoubleUtils.add(totalGoodsMoney, deliveryPrice);//订单总金额+配送费
                }
            }

            //如果店铺有奖励金
            if (shopAwardMoney > 0) {
                shopTotalMoney = JYMathDoubleUtils.sub(shopTotalMoney, shopAwardMoney);//订单所有的钱 减去店铺奖励的金额
            }

            if (ValidateUtil.isAbsDouble(shopRate)) { //单独设置了店铺分成比例

            } else { //没有单独设置  按平台比例
                if (0 == 1 - orderInfo.getIsZiQu()) { //自取订单  无配送费

                    if (null == SYS_SETTINGS.SHOP_RATE_DAODIAN) {
                        System.out.println("未设置到店消费类店铺分成比例");
                        return new ResultInfo("操作失败，请稍后再试。2");
                    }
                    shopRate = Double.parseDouble(SYS_SETTINGS.SHOP_RATE_DAODIAN + "");
                } else { //配送类订单
                    if (null == SYS_SETTINGS.SHOP_RATE_PEISONG) {
                        System.out.println("未设置配送类店铺分成比例");
                        return new ResultInfo("操作失败，请稍后再试。3");
                    }
                    shopRate = Double.parseDouble(SYS_SETTINGS.SHOP_RATE_PEISONG + "");
                }
            }

            if (null != SYS_SETTINGS.SHARE_SHOP_PACKET_MONEY && 0 == 1 - SYS_SETTINGS.SHARE_SHOP_PACKET_MONEY) {
                shopTotalMoney = JYMathDoubleUtils.add(shopTotalMoney, packetPrice);//打包费参与分成
            }
            // 税
            if (null == SYS_SETTINGS.IS_SHARE_TAX_MONEY) {
                System.out.println("平台未设置税费是否分成");
            }

            if (null != SYS_SETTINGS.IS_SHARE_TAX_MONEY && 0 == 1 - SYS_SETTINGS.IS_SHARE_TAX_MONEY
                    && taxMoney != null && taxMoney > 0) { // 有税费参与分成
                shopTotalMoney = JYMathDoubleUtils.add(shopTotalMoney, taxMoney);
            }
            shopMoney = JYMathDoubleUtils.mul(shopTotalMoney, JYMathDoubleUtils.div(shopRate, 100));//分配金额  此时orderTotalMoney是订单所有的钱 减掉不应该有的配送费 再减掉店铺奖励的金额了

            // 配送费减免的部分不参与分成 在店铺得到的总金额中减去
            if (0 == orderInfo.getIsZiQu()) {//配送订单 且平台配送的
                if (null != shopInfo && (null == shopInfo.getIsSelfPost() || 0 == shopInfo.getIsSelfPost())) {
                    //平台配送
                    //店铺金额减掉承担的配送费免减
                    if (ValidateUtil.isAbsDouble(orderInfo.getOriginalYunFeiShop())) {
                        shopMoney = JYMathDoubleUtils.sub(shopMoney, orderInfo.getOriginalYunFeiShop());//店铺总金额-店铺减免的配送费
                    }
                }
            }

            if (null != SYS_SETTINGS.SHARE_SHOP_PACKET_MONEY && 0 == SYS_SETTINGS.SHARE_SHOP_PACKET_MONEY) {
                shopMoney = JYMathDoubleUtils.add(shopMoney, packetPrice);//打包费不参与分成 直接给商家所有钱
            }
            if (null != SYS_SETTINGS.IS_SHARE_TAX_MONEY && 0 == SYS_SETTINGS.IS_SHARE_TAX_MONEY
                    && taxMoney != null && taxMoney > 0) { // 有税费不参与分成 店铺所有
                shopMoney = JYMathDoubleUtils.add(shopMoney, taxMoney);
            }

        } else if (null != orderInfo.getOrderType()
                && 0 == ORDER_TYPE.SERVICE_LOCK - orderInfo.getOrderType()) {//跑腿订单
            shopTotalMoney = 0d;
        }
        //2. 配送员部分
        if (0 == orderInfo.getIsZiQu()) { //配送的订单才进来
            if (null == SYS_SETTINGS.POSTMAN_SHARE_MONEY) {
                System.out.println("未设置配送员是否参与分成");
                return new ResultInfo("操作失败，请稍后再试。4");
            }

            //如果店铺是自配送的  则无需再处理配送费部分
            if ((null != shopInfo && null != shopInfo.getIsSelfPost() && 0 != 1 - shopInfo.getIsSelfPost())
                    || hasPostman
            ) {
                Integer postManShare = SYS_SETTINGS.POSTMAN_SHARE_MONEY; //配送员分成类型（0不参与，1总金额，2参与配送费部分）
                switch (postManShare) {
                    case SysSettingValueKey.POSTMAN_SHARE_NONE: {//不参与分成
                        postmanRate = 0d;
                    }
                    break;
                    case SysSettingValueKey.POSTMAN_SHARE_ALL: {//参与订单总金额分成
                        Double totalMoney = orderInfo.getTotalMoney();//订单总金额
                        if (null == SYS_SETTINGS.POSTMAN_RATE) {
                            System.out.println("未设置配送员分成比例");
                            return new ResultInfo("操作失败，请稍后再试。5");
                        }
                        postmanRate = Double.parseDouble(SYS_SETTINGS.POSTMAN_RATE + "");//配送员分成比例
                        if (ValidateUtil.isNotNull(orderInfo.getPostManUsername())) {
                            CityPostman cityPostman = CityPostmanMemory.getInstance().getPostman(orderInfo.getPostManUsername());
                            if (null != cityPostman && ValidateUtil.isAbsDouble(cityPostman.getMoneyRate())) {
                                postmanRate = cityPostman.getMoneyRate();
                            }
                        }
                        if (ValidateUtil.isAbsDouble(postmanRate)) {
                            postmanMoney = JYMathDoubleUtils.mul(totalMoney, JYMathDoubleUtils.div(postmanRate, 100));
                        }
                    }
                    break;
                    case SysSettingValueKey.POSTMAN_SHARE_DELIVERY: { //参与配送费部分
                        if (null == SYS_SETTINGS.POSTMAN_RATE) {
                            System.out.println("未设置配送员分成比例");
                            return new ResultInfo("操作失败，请稍后再试。5");
                        }
                        postmanRate = Double.parseDouble(SYS_SETTINGS.POSTMAN_RATE + "");//配送员分成比例
                        if (ValidateUtil.isNotNull(orderInfo.getPostManUsername())) {
                            CityPostman cityPostman = CityPostmanMemory.getInstance().getPostman(orderInfo.getPostManUsername());
                            if (null != cityPostman && ValidateUtil.isAbsDouble(cityPostman.getMoneyRate())) {
                                postmanRate = cityPostman.getMoneyRate();
                            }
                        }
                        if (ValidateUtil.isAbsDouble(postmanRate)) {
                            postmanMoney = JYMathDoubleUtils.mul(deliveryPrice, JYMathDoubleUtils.div(postmanRate, 100));
                        }
                    }
                    break;
                }
            }
        }
        // 小费计算
        // create by ytk   : star
        Double tipMoney = orderInfo.getTipMoney();
        if (null == tipMoney) {
            tipMoney = 0d;
        }
        if (tipMoney != null && tipMoney > 0) { // 有小费
            if (SYS_SETTINGS.SHARE_TIP_MONEY != null && SYS_SETTINGS.SHARE_TIP_MONEY > 0) {
                switch (SYS_SETTINGS.SHARE_TIP_MONEY) {
                    case 1:
                        // 店铺 all
                        shopMoney = JYMathDoubleUtils.add(shopMoney, tipMoney);
                        break;
                    case 2:
                        // 骑手 all
                        if (orderInfo.getIsZiQu() == 0  // 配送订单
                                && null != SYS_SETTINGS.POSTMAN_SHARE_MONEY
                                && SYS_SETTINGS.POSTMAN_SHARE_MONEY != SysSettingValueKey.POSTMAN_SHARE_NONE) {  //  参与 配送费分成
                            postmanMoney = JYMathDoubleUtils.add(postmanMoney, tipMoney);
                        }
                        break;
                    case 3:
                        // 店铺 some  骑手 no
                        if (null != shopRate && shopRate > 0) {
                            shopMoney = JYMathDoubleUtils.add(shopMoney, JYMathDoubleUtils.mul(tipMoney, JYMathDoubleUtils.div(shopRate, 100)));
                        }
                        break;
                    case 4:
                        // 店铺 some 骑手 some
                        if (orderInfo.getIsZiQu() == 0  // 自取
                                && (null != shopInfo && null != shopInfo.getIsSelfPost() && 0 != 1 - shopInfo.getIsSelfPost())  // 平台配送
                                && null != SYS_SETTINGS.POSTMAN_SHARE_MONEY
                                && SYS_SETTINGS.POSTMAN_SHARE_MONEY != SysSettingValueKey.POSTMAN_SHARE_NONE) {  //  参与 配送费分成
                            postmanMoney = JYMathDoubleUtils.add(postmanMoney, JYMathDoubleUtils.mul(tipMoney, JYMathDoubleUtils.div(postmanRate, 100)));
                        }
                        if (null != shopRate && shopRate > 0) {
                            shopMoney = JYMathDoubleUtils.add(shopMoney, JYMathDoubleUtils.mul(tipMoney, JYMathDoubleUtils.div(shopRate, 100)));
                        }
                        break;
                    case 5:
                        // 店铺 0  骑手 some
                        if (orderInfo.getIsZiQu() == 0  // 自取
                                && null != SYS_SETTINGS.POSTMAN_SHARE_MONEY
                                && SYS_SETTINGS.POSTMAN_SHARE_MONEY != SysSettingValueKey.POSTMAN_SHARE_NONE) {  //  参与 配送费分成
                            postmanMoney = JYMathDoubleUtils.add(postmanMoney, JYMathDoubleUtils.mul(tipMoney, JYMathDoubleUtils.div(postmanRate, 100)));
                        }
                        break;
                    case 6:
                        // 店铺 0  骑手0
                        break;
                    default:
                        break;
                }
            }
        }
        // end

        //业务员分成
        Double businessRate = 0d; //业务员分成比例
        Double businessMoney = 0d;//业务员分成金额
        //获取店铺的业务员
        if (ValidateUtil.isID(orderInfo.getShopId())) {
            String managerUsername = ShopManagerRelationMemory.getInstance().getManagerByShopId(orderInfo.getShopId());
            UserInfo managerInfo = UserInfoMemory.getInstance().getUserInfo(managerUsername);
            if (null != managerInfo && ValidateUtil.isAbsDouble(managerInfo.getRate())) {
                businessRate = managerInfo.getRate();
                //分成支付金额部分
                businessMoney = JYMathDoubleUtils.mul(payMoney, JYMathDoubleUtils.div(businessRate, 100));//分配金额
            }
        }


        //3. 平台分成金额
        Double platformRate = JYMathDoubleUtils.sub(JYMathDoubleUtils.sub(100, shopRate), postmanRate);//平台分成比例
        platformRate = JYMathDoubleUtils.sub(platformRate, businessRate);

        Double platformMoney = JYMathDoubleUtils.sub(JYMathDoubleUtils.sub(payMoney, shopMoney), postmanMoney);  // 平台收入 = 支付金额-分成给店铺-分成给配送员-分给业务员
        platformMoney = JYMathDoubleUtils.sub(platformMoney, businessMoney);
        StringBuffer sb = new StringBuffer();
        sb.append("update ").append(PojoTables.OrderPay).append(" set ")
                .append("shopRate = ").append(JYMathDoubleUtils.div(shopRate, 100)).append(",shopMoney=").append(shopMoney)
                .append(",postmanRate= ").append(JYMathDoubleUtils.div(postmanRate, 100)).append(",postmanMoney=").append(postmanMoney)
                .append(",businessRate=").append(JYMathDoubleUtils.div(businessRate, 100)).append(",businessMoney =").append(businessMoney)
                .append(",platformRate=").append(JYMathDoubleUtils.div(platformRate, 100)).append(",platformMoney=").append(platformMoney)
                .append(",updateUser='").append(orderInfo.getPostManUsername()).append("'")
                .append(" where orderNo='").append(orderNo).append("'");
        try {
            UserDaoSql.getInstance().executeBySql(sb.toString());
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultInfo("支付更新失败");
        }
        //缓存流水
        OrderPayMemory.getInstance().modify(orderNo);
        try {
            JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.ORDER_PAY_MODIFY).setStr01(orderNo);
            JmsSender.setTopicSender(notify);
        } catch (Exception e) {
        }
        return new ResultInfo();
    }


    //保存工单价格等信息
    private ResultInfo finishOrder(String orderNo, String itemsJson, String opUsername) {
        //解析订单项目
        List<OrderItems> itemList = null;
        if (ValidateUtil.isNotNull(itemsJson)) {
            try {
                itemsJson = itemsJson.replace("\\", "");
                itemList = new Gson().fromJson(itemsJson, new TypeToken<List<OrderItems>>() {
                }.getType());
            } catch (Exception e) {
                e.printStackTrace();
                return new ResultInfo("项目解析有误，请稍后再试");
            }
        }

        //清除原有的项目
        StringBuilder itemSb = new StringBuilder();
        itemSb.append("update ").append(PojoTables.ORDER_ITEMS).append(" set delFlag = 1,updateUser = '").append(opUsername)
                .append("' where delFlag = 0 and orderNo ='").append(orderNo).append("'");
        try {
            UserDaoSql.getInstance().executeBySql(itemSb.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return new ResultInfo("修改信息失败，请稍后再试");
        }

        //保存订单项目
        int count = 0;
        Double orderMoney = 0d;
        //2. 存储商品
        if (ValidateUtil.isAbsList(itemList)) {
            for (int i = 0; i < itemList.size(); i++) {
                if (null == itemList.get(i)) {
                    continue;
                }
                if (null == itemList.get(i).getTotalCount()) {
                    itemList.get(i).setTotalCount(1);
                }
                itemList.get(i).setOrderNo(orderNo);
                itemList.get(i).setCreateTime(DateUtils.getCurrTime());
                itemList.get(i).setCreateUser(opUsername);
                itemList.get(i).setId(null);
                itemList.get(i).setTotalMoney(JYMathDoubleUtils.mul(itemList.get(i).getPrice(), itemList.get(i).getTotalCount()));
                orderMoney = JYMathDoubleUtils.add(orderMoney, itemList.get(i).getPrice());
                try {
                    UserDaoSql.getInstance().insertObj(PojoTables.ORDER_ITEMS, itemList.get(i));
                } catch (SQLException e) {
                    e.printStackTrace();
                    return new ResultInfo("存储信息失败，请稍后再试");
                }
                count++;
            }
        }
        //添加项目到缓存
        OrderItemsMemory.getInstance().addGoods(orderNo);


        //更新订单信息
        StringBuilder sb = new StringBuilder();
        sb.append("update ").append(PojoTables.OrderInfo).append(" set totalPrice =").append(orderMoney).append(",totalMoney=").append(orderMoney).append(",updateUser ='").
                append(opUsername).append("' where orderNo = '").append(orderNo).append("' and delFlag=0");
        try {
            UserDaoSql.getInstance().executeBySql(sb.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return new ResultInfo("更新订单信息失败，请稍后再试");
        }

        //更新订单信息到缓存
        OrderInfoMemory.getInstance().modifyStatus(orderNo);

        //更新订单信息
        StringBuilder sbPre = new StringBuilder();
        sbPre.append("update ").append(PojoTables.ORDER_INFO_PRE).append(" set totalCount=").append(count).append(",totalPrice =").append(orderMoney).append(",updateUser ='").
                append(opUsername).append("',orderStatus=").append(ORDER_STATUS.POSTMAN_FINISH).append(",postmanFinishTime=").append(DateUtils.getCurrTime()).append(" where orderNo = '").append(orderNo).append("' and delFlag=0");
        try {
            UserDaoSql.getInstance().executeBySql(sbPre.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return new ResultInfo("更新订单信息失败，请稍后再试");
        }

        //更新订单信息到缓存
        OrderInfoMemory.getInstance().modifyStatus(orderNo);


        return new ResultInfo();
    }


    //配送员异常上报
    @RequestMapping(method = RequestMethod.POST, value = "/postman/order/trouble")
    @ResponseBody
    public String order_postman_trouble(String token, String orderNo, String reason,
                                        Double lat, Double lng, String troubleType,
                                        String province, String city, String county, String address) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        if (ValidateUtil.isNull(orderNo)) {
            return AjaxResult.errorResult("请选择订单");
        }

        OrderInfo orderInfo = OrderInfoMemory.getInstance().getOrderInfo(orderNo);
        if (null == orderInfo) {
            return AjaxResult.errorResult("该订单不存在");
        }

        //该订单是否已经转给别人
        if (ValidateUtil.isNotNull(orderInfo.getChangePostman())) {
            return AjaxResult.errorResult("您已发起转单请求，请等待对方应答");
        }
        if (StringUtils.isEmpty(troubleType) || !troubleType.equals(ORDER_TROUBLE_TYPE.POINT_TROUBLE)) {
            troubleType = ORDER_TROUBLE_TYPE.DEFAULT;
        }
        //判断订单状态是否可以操作
        if (ORDER_STATUS.OVER == orderInfo.getOrderStatus()
                || ORDER_STATUS.CANCEL == orderInfo.getOrderStatus()
                || ORDER_STATUS.SUBMIT == orderInfo.getOrderStatus()
                || ORDER_STATUS.PAYED_CANCEL == orderInfo.getOrderStatus()
                || ORDER_STATUS.SHOP_FINISH == orderInfo.getOrderStatus()
                || ORDER_STATUS.POSTMAN_FINISH == orderInfo.getOrderStatus()
                || ORDER_STATUS.POSTMAN_REFUSED == orderInfo.getOrderStatus()
                || ORDER_STATUS.SHOP_REFUSED == orderInfo.getOrderStatus()) {
            return AjaxResult.errorResult("该状态不允许操作");
        }
        if (troubleType.equals(ORDER_TROUBLE_TYPE.POINT_TROUBLE)) {
            QueryCondition query = QueryCondition.getInstance();
            query.addCondition(Expression.getInstance().addChild("delFlag", 0).addChild("username", user.getUsername()).addChild("orderNo", orderNo));
            Long count = 0l;
            String sql = DaoUtils.getSqlCount(PojoTables.ORDER_POSTMAN_TROUBLE, query);
            try {
                count = UserDaoSql.getInstance().getCount(sql);
            } catch (SQLException e) {
                e.printStackTrace();
            }
            if (count > 5) {
                return AjaxResult.errorResult("该订单您已上报了两次异常，无法再次上传");
            }

            if (StringUtils.isEmpty(reason)) {
                reason = "定位异常上报";
            }
            Long time = DateUtils.getCurrTime();
            OrderPostmanTrouble info = new OrderPostmanTrouble();
            info.setOrderNo(orderNo);
            info.setTroubleReason(reason);
            if (ValidateUtil.isLatLng(lat, lng)) {
                info.setLat(lat);
                info.setLng(lng);
            }
            info.setTroubleType(troubleType);
            info.setCreateTime(time);
            info.setDelFlag(0);
            info.setUsername(user.getUsername());
            info.setCreateUser(user.getUsername());

            if (ValidateUtil.isNotNull(province) || ValidateUtil.isNotNull(city) || ValidateUtil.isNotNull(address)) {
                info.setProvince(province);
                info.setCity(city);
                info.setCounty(county);
                info.setAddress(address);
            }
            try {
                UserDaoSql.getInstance().insertObj(PojoTables.ORDER_POSTMAN_TROUBLE, info);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        } else {
            QueryCondition query = QueryCondition.getInstance();
            query.addCondition(Expression.getInstance().addChild("delFlag", 0).addChild("username", user.getUsername()).addChild("orderNo", orderNo));
            Long count = 0l;
            String sql = DaoUtils.getSqlCount(PojoTables.ORDER_POSTMAN_TROUBLE, query);
            try {
                count = UserDaoSql.getInstance().getCount(sql);
            } catch (SQLException e) {
                e.printStackTrace();
            }
            if (count > 2) {
                return AjaxResult.errorResult("该订单您已上报了两次异常，无法再次上传");
            }
            Long time = DateUtils.getCurrTime();
            OrderPostmanTrouble info = new OrderPostmanTrouble();
            info.setOrderNo(orderNo);
            info.setTroubleReason(reason);
            if (ValidateUtil.isLatLng(lat, lng)) {
                info.setLat(lat);
                info.setLng(lng);
            }
            info.setTroubleType(troubleType);
            info.setCreateTime(time);
            info.setDelFlag(0);
            info.setUsername(user.getUsername());
            info.setCreateUser(user.getUsername());

            if (ValidateUtil.isNotNull(province) || ValidateUtil.isNotNull(city) || ValidateUtil.isNotNull(address)) {
                info.setProvince(province);
                info.setCity(city);
                info.setCounty(county);
                info.setAddress(address);
            } else {
                try {
                    GeoAddressDetail addressDetail = Geohash.getAddressDetail(lat, lng);
                    System.out.println("上报异常订单~~~~:" + addressDetail != null);
                    if (null != addressDetail) {
                        info.setProvince(addressDetail.getShortProvince());
                        String cityStr = addressDetail.getCity();
                        if (ValidateUtil.isNotNull(cityStr)) {
                            cityStr = SysCommon.removeShi(cityStr);
                            info.setCity(cityStr);
                        }
                        info.setCounty(addressDetail.getCounty());
                        info.setAddress(addressDetail.getShortAddress());
                        System.out.println("省" + addressDetail.getShortProvince());
                        System.out.println("市" + addressDetail.getCity());
                        System.out.println("区" + addressDetail.getCounty());
                        System.out.println("地址" + addressDetail.getShortAddress());
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                UserDaoSql.getInstance().insertObj(PojoTables.ORDER_POSTMAN_TROUBLE, info);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        //检测该配送员已经上报了异常
        StringBuilder sql = new StringBuilder();
        sql.append(" update ").append(PojoTables.OrderInfo).append(" set isTroubleOrder = 1 ").append(", updateUser ='").append(user.getUsername()).append("' ").append(" where delFlag = 0 and orderNo = '").append(orderInfo.getOrderNo()).append("' ");
        try {
            UserDaoSql.getInstance().executeBySql(sql.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        //跑腿订单 更新跑腿订单信息里的状态
        if (null != orderInfo.getOrderType() && (
                0 == ORDER_TYPE.PAO_TUI - orderInfo.getOrderType()
                        || 0 == ORDER_TYPE.DAI_GOU - orderInfo.getOrderType()
                        || 0 == ORDER_TYPE.BANG_BAN - orderInfo.getOrderType()
                        || 0 == ORDER_TYPE.PERSON_TRANSPORT - orderInfo.getOrderType()
                        || 0 == ORDER_TYPE.HUO_YUN - orderInfo.getOrderType())
        ) {//跑腿订单
            StringBuilder sbOther = new StringBuilder();
            sbOther.append("update ").append(PojoTables.OTHER_ORDER_INFO).append(" set  isTroubleOrder=1").append(",updateUser='")
                    .append(user.getUsername()).append("' where delFlag =0 and  orderNo = '").append(orderNo).append("'");
            try {
                UserDaoSql.getInstance().executeBySql(sbOther.toString());
            } catch (SQLException e) {
                e.printStackTrace();
            }
            //缓存修改
            OtherOrderMemory.getInstance().addOrModify(orderNo);
        }
        OrderInfoMemory.getInstance().modifyStatus(orderNo);
        try {
            JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.ORDER_PAY_MODIFY).setStr01(orderNo);
            JmsSender.setTopicSender(notify);
        } catch (Exception e) {
        }
        return AjaxResult.successResult();
    }

    // 二级骑手相关操作--------------------------------------------------
    // 二级骑手抢单
    @RequestMapping(method = RequestMethod.POST, value = "/secondary/postman/order/grab")
    @ResponseBody
    public String order_secondary_postman_new_list_grab(String token, String sysAppKey, String orderNo) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        CityPostman postman = CityPostmanMemory.getInstance().getPostman(user.getUsername());
        if (null == postman) {
            return AjaxResult.errorResult("未查询到您的信息，无法操作");
        }

        //0 锁定  1未锁定
        if (null != postman.getIsLock() && 0 == 1 - postman.getIsLock()) {
            return AjaxResult.errorResult("您已被锁定，无法接单");
        }

        if (ValidateUtil.isNotAbsInteger(postman.getIsWork())) {
            return AjaxResult.errorResult("您无法接单，请先上班");
        }
        if (0 == postman.getIsWork()) {
            return AjaxResult.errorResult("请先上班");
        }
        // 二级骑手检测
        if (postman.getType() == null || postman.getType() != POSTMAN_TYPE.POSTMAN_2) {
            return AjaxResult.errorResult("你不是众包端骑手");
        }

        if (null != SYS_SETTINGS.POSTMAN_MUST_VERIFY && 0 == 1 - SYS_SETTINGS.POSTMAN_MUST_VERIFY
                && (null == postman.getIsVerify() || 0 != 1 - postman.getIsVerify())) {
            return AjaxResult.errorResult("您尚未通过认证，请先去认证");
        }
        if (null != SYS_SETTINGS.POSTMAN_MUST_VERIFY_FACE && 0 == 1 - SYS_SETTINGS.POSTMAN_MUST_VERIFY_FACE) {
            if (null != user.getIsCert() && 0 == 1 - user.getIsCert()) {
                //已认证
            } else {
                return AjaxResult.errorResult("未通过实名认证，请先去认证");
            }
        }


//        if (null != SYS_SETTINGS.POSTMAN_CAM_GRAB_ORDER && SYS_SETTINGS.POSTMAN_CAM_GRAB_ORDER > 0) {
//            int count = OrderInfoMemory.getInstance().getPostmanIngOrderCount(user.getUsername());
//            if (count - SYS_SETTINGS.POSTMAN_CAM_GRAB_ORDER >= 0) {
//                return AjaxResult.errorResult("您有未完成订单，无法继续抢单");
//            }
//        }
        // 必须缴纳？
        if (null != SYS_SETTINGS.POSTMAN_MUST_DEPOSIT && 0 == 1 - SYS_SETTINGS.POSTMAN_MUST_DEPOSIT) {
            //验证押金金额是否满足
            UserWallet userWallet = UserWalletMemory.getInstance().getWallet(user.getUsername());
            if (null == userWallet) {
                return AjaxResult.errorResult("您还未缴纳押金，请先缴纳押金");
            }
            if (null == userWallet.getDepositMoney() || userWallet.getDepositMoney() <= 0) {
                return AjaxResult.errorResult("您还未缴纳押金，请先缴纳押金！");
            }
            //必须缴纳的押金金额
            Double money = SysConfigDepositMemory.getInstance().getByType(UserType.POSTMAN);
            if (null == money) {
                money = 0d;
            }
            if (JYMathDoubleUtils.sub(userWallet.getDepositMoney(), money) < 0) {
                return AjaxResult.errorResult("您缴纳的押金不足，请先缴纳押金");
            }
        }


        OrderInfo orderInfo = OrderInfoMemory.getInstance().getOrderInfo(orderNo);
        if (null == orderInfo) {
            return AjaxResult.errorResult("当前订单不存在");
        }
        if (ValidateUtil.isNotNull(orderInfo.getSecondaryPostManUsername())) {
            return AjaxResult.errorResult("该订单已被抢");
        }
//        if (orderInfo.getOrderStatus() == ORDER_STATUS.POSTMAN_PICK_POINT) {
//            return AjaxResult.errorResult("已送达提货点无法抢单");
//        }
        //验证抢单范围
        if (null != SYS_SETTINGS.CHECK_POSTMAN_GRAB_RANGE && SYS_SETTINGS.CHECK_POSTMAN_GRAB_RANGE > 0) {//验证配送员抢单范围 0不验证 1验证取货地址 2验证收货地址
            if (null != SYS_SETTINGS.DELIVERY_RANGE && SYS_SETTINGS.DELIVERY_RANGE > 0) {
                PostmanPositionInfo positionInfo = PostmanPositionMemory.getInstance().get(postman.getId());
                if (null == positionInfo) {
                    return AjaxResult.errorResult("未定位到您的位置，无法抢单");
                }
                if (0 == 1 - SYS_SETTINGS.CHECK_POSTMAN_GRAB_RANGE) {//1验证取货地址
                    if (ValidateUtil.isAbsDouble(positionInfo.getLat()) && ValidateUtil.isAbsDouble(positionInfo.getLng())
                            && ValidateUtil.isAbsDouble(orderInfo.getLat()) && ValidateUtil.isAbsDouble(orderInfo.getLng())) {
                        Double distinct = Geohash.distance(positionInfo.getLat(), positionInfo.getLng(), orderInfo.getLat(), orderInfo.getLng());
                        if (ValidateUtil.isNotAbsDouble(distinct)) {
                            return AjaxResult.errorResult("未获取到距离，无法抢单");
                        }
                        if (distinct - SYS_SETTINGS.DELIVERY_RANGE > 0) {
                            return AjaxResult.errorResult("您已超出可接单范围");
                        }
                    }
                } else if (0 == 2 - SYS_SETTINGS.CHECK_POSTMAN_GRAB_RANGE) {//2验证收货地址
                    if (ValidateUtil.isAbsDouble(positionInfo.getLat()) && ValidateUtil.isAbsDouble(positionInfo.getLng())
                            && ValidateUtil.isAbsDouble(orderInfo.getShopLat()) && ValidateUtil.isAbsDouble(orderInfo.getShopLng())) {
                        Double distinct = Geohash.distance(positionInfo.getLat(), positionInfo.getLng(), orderInfo.getShopLat(), orderInfo.getShopLng());
                        if (ValidateUtil.isNotAbsDouble(distinct)) {
                            return AjaxResult.errorResult("未获取到距离，无法抢单");
                        }
                        if (distinct - SYS_SETTINGS.DELIVERY_RANGE > 0) {
                            return AjaxResult.errorResult("您已超出可接单范围");
                        }
                    }
                }
            }
        }

        int oStatus = ORDER_STATUS.SECONDARY_POSTMAN_SURE_AFTER_P_SUER; // 默认骑手抢单后 抢单
        //判断订单状态  是否可以抢单
        if (OrderMan.isUnSecondaryDelivery(orderInfo)) {
            // 未抢订单

        } else {
            return AjaxResult.errorResult("当前订单已被抢");
        }

        // 二级骑手是否抢过是否已抢过
        if (SecondaryPostmanGrabMemory.getInstance().hasGrabThisOrder(user.getUsername(), orderNo)) {
            SecondaryPostmanGrabMemory.getInstance().delThisOrderGrabInfo(user.getUsername(),orderNo);
            return AjaxResult.errorResult("你已经抢过该订单，请耐心等待");
        }

        //判断当前订单是否被其他人抢过
        if (SecondaryPostmanGrabMemory.getInstance().hasGrab(orderNo)) {
            return AjaxResult.errorResult("该订单已被其他配送员抢了");
        }

        // 抢单数量限制
        if (!canGrabOrder(user.getUsername(), orderInfo.getAgentId(), orderNo)) {
//            return AjaxResult.errorResult("您有未完成订单，无法继续抢单");
            return AjaxResult.errorResult("您接单数已达上限，如需接单请联系管理员");
        }

        long time = DateUtils.getCurrTime();
        //将抢单信息加入到缓存
        OrderGrabInfo orderGrabInfo = new OrderGrabInfo(user.getUsername(), user.getName(), time, orderNo, orderInfo.getShopCity());
        SecondaryPostmanGrabMemory.getInstance().grabOrder(orderGrabInfo);

        String postmanPhone = user.getTelPhone();
        if (ValidateUtil.isNull(postmanPhone)) {
            postmanPhone = user.getUsername();
        }
        String poto = user.getSignPhoto();
        if (ValidateUtil.isNotNull(poto) && ValidateUtil.isNetUrl(poto)) {
            poto = poto.replace(SYS_CONFIG_PATH.IMAGE_BASE_URL, "");
        }
        if (orderInfo.getIsSeriesSaleShop() == SHOP_SERIESSALE_TYPE.SERIESSALE_SHOP) {
            if (orderInfo.getShopSelfPost() == 0) {
                if (orderInfo.getOrderStatus() == ORDER_STATUS.POSTMAN_SURE) {
                    oStatus = ORDER_STATUS.SECONDARY_POSTMAN_SURE_AFTER_P_SUER;
                } else if (orderInfo.getOrderStatus() == ORDER_STATUS.POSTMAN_DAODIAN) {
                    oStatus = ORDER_STATUS.SECONDARY_POSTMAN_SURE_AFTER_P_DAODIAN;
                } else if (orderInfo.getOrderStatus() == ORDER_STATUS.POSTMAN_PULL_GOODS) {
                    oStatus = ORDER_STATUS.SECONDARY_POSTMAN_SURE_AFTER_P_PULL;
                } else if (orderInfo.getOrderStatus() == ORDER_STATUS.POSTMAN_PICK_POINT) {
                    oStatus = ORDER_STATUS.SECONDARY_POSTMAN_SURE_AFTER_P_POINT;
                }
            } else {
                if (orderInfo.getOrderStatus() == ORDER_STATUS.POSTMAN_PICK_POINT) {
                    oStatus = ORDER_STATUS.SECONDARY_POSTMAN_SURE_AFTER_P_POINT;
                }
            }
        } else {
            // 校内商家
            if (orderInfo.getShopSelfPost() == 1) {
                return AjaxResult.errorResult("自配送商家不能抢单");
            } else {
                oStatus = ORDER_STATUS.SECONDARY_POSTMAN_SURE_AFTER_INNER_SHOP;
            }
        }
        StringBuilder sb = new StringBuilder();
        sb.append("update ").append(PojoTables.OrderInfo).append(" set orderStatus = ").append(oStatus)
                .append(",updateUser='").append(user.getUsername()).append("',secondaryPostManUsername='")
                .append(user.getUsername()).append("',secondaryPostmanName='").append(user.getName()).append("',secondaryPostmanPhone='").append(postmanPhone)
                .append("',secondaryPostmanImageUrl='").append(poto).append("',secondaryPostmanSureTime=").append(time).append(" where delFlag=0 and orderNo = '").append(orderNo).append("'");
        OrderStatus orderStatus = new OrderStatus(orderNo, oStatus, user.getUsername(), time);
        try {
            UserDaoSql.getInstance().insertObj(PojoTables.OrderStatus, orderStatus);
            UserDaoSql.getInstance().executeBySql(sb.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("操作失败，请稍后重试");
        }
        //订单状态缓存
        OrderStatusMemory.getInstance().addStatus(orderNo);
        //修改缓存
        OrderInfoMemory.getInstance().modifyStatus(orderNo);
        if (null != orderInfo.getOrderType()) {
            Notice.publishNotice2Person(sysAppKey, orderInfo.getUsername(), JPushMessage.USER, NoticeType.order, "订单信息", "您的订单（订单编号：" + orderNo + "），已有众包端抢单了，请耐心等待");
        }
        return AjaxResult.successResult();
    }


    // 二级骑手标记为已取货
    @RequestMapping(method = RequestMethod.POST, value = "/secondary/order/postman/pull")
    @ResponseBody
    public String order_secondary_postman_pull(String token, String orderNo, String verifyCode) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        OrderInfo orderInfo = null;
        if (ValidateUtil.isNotNull(verifyCode)) {
            orderInfo = OrderInfoMemory.getInstance().getOrderInfoByVerifyCode(verifyCode);
        }
        if (orderInfo == null) {
            orderInfo = OrderInfoMemory.getInstance().getOrderInfo(orderNo);
        }
        if (null == orderInfo) {
            return AjaxResult.errorResult("该订单不存在");
        }
        // 必须缴纳？
        if (null != SYS_SETTINGS.POSTMAN_MUST_DEPOSIT && 0 == 1 - SYS_SETTINGS.POSTMAN_MUST_DEPOSIT) {
            //验证押金金额是否满足
            UserWallet userWallet = UserWalletMemory.getInstance().getWallet(user.getUsername());
            if (null == userWallet) {
                return AjaxResult.errorResult("您还未缴纳押金，请先缴纳押金");
            }
            if (null == userWallet.getDepositMoney() || userWallet.getDepositMoney() <= 0) {
                return AjaxResult.errorResult("您还未缴纳押金，请先缴纳押金！");
            }
            //必须缴纳的押金金额
            Double money = SysConfigDepositMemory.getInstance().getByType(UserType.POSTMAN);
            if (null == money) {
                money = 0d;
            }
            if (JYMathDoubleUtils.sub(userWallet.getDepositMoney(), money) < 0) {
                return AjaxResult.errorResult("您缴纳的押金不足，请先缴纳押金");
            }
        }

        int status = orderInfo.getOrderStatus();
        if (status != ORDER_STATUS.SECONDARY_POSTMAN_SURE_AFTER_P_POINT // 送达提货点后抢的单
                && status != ORDER_STATUS.POSTMAN_PICK_POINT // 或者到达提货点
                && status != ORDER_STATUS.SECONDARY_POSTMAN_SURE_AFTER_INNER_SHOP // 校内商家平台配送订单
        ) {
            return AjaxResult.errorResult("当前订单状态下不允许操作");
        }

        if (StringUtils.isNotEmpty(orderInfo.getSecondaryPostManUsername()) && !user.getUsername().equalsIgnoreCase(orderInfo.getSecondaryPostManUsername())) {
            return AjaxResult.errorResult("该订单不是您的，无法操作");
        }
        // 判断是否送达提货点
        if (orderInfo.getIsSeriesSaleShop() == SHOP_SERIESSALE_TYPE.INNER_SHOP) {

        } else {
            if (orderInfo.getPostmanPostPointTime() == null || ValidateUtil.isNotAbsLong(orderInfo.getPostmanPostPointTime())) {
                return AjaxResult.errorResult("骑手未送达提货点");
            }
        }
//        if (orderInfo.getPostmanPostPointTime() == null || ValidateUtil.isNotAbsLong(orderInfo.getPostmanPostPointTime())) {
//            return AjaxResult.errorResult("骑手未送达提货点");
//        }
        Long tim = DateUtils.getCurrTime();
        String postmanPullTime = ",secondaryPostmanPullTime=" + tim;

        String postmanSureTime = "";
        if (ValidateUtil.isNotAbsLong(orderInfo.getSecondaryPostmanSureTime())) {
            postmanSureTime = ",secondaryPostmanSureTime=" + tim;
        }
        String postmanPhone = user.getTelPhone();
        if (ValidateUtil.isNull(postmanPhone)) {
            postmanPhone = user.getUsername();
        }
        String poto = user.getSignPhoto();
        if (ValidateUtil.isNotNull(poto) && ValidateUtil.isNetUrl(poto)) {
            poto = poto.replace(SYS_CONFIG_PATH.IMAGE_BASE_URL, "");
        }
        StringBuilder sb = new StringBuilder();
        sb.append("update ").append(PojoTables.OrderInfo).append(" set updateUser='").append(user.getUsername()).append("'")
                .append(postmanPullTime).append(postmanSureTime).append(",orderStatus=").append(ORDER_STATUS.SECONDARY_POSTMAN_PULL_GOODS)
                .append(",secondaryPostManUsername='")
                .append(user.getUsername()).append("',secondaryPostmanName='").append(user.getName()).append("',secondaryPostmanPhone='").append(postmanPhone)
                .append("',secondaryPostmanImageUrl='").append(poto).append("' where delFlag=0 and orderNo = '").append(orderNo).append("'");
        OrderStatus orderStatus = new OrderStatus(orderNo, ORDER_STATUS.SECONDARY_POSTMAN_PULL_GOODS, user.getUsername(), tim);
        try {
            UserDaoSql.getInstance().executeBySql(sb.toString());
            UserDaoSql.getInstance().insertObj(PojoTables.OrderStatus, orderStatus);
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("操作失败，请稍后重试");
        }
        // 移除验证码
        if (ValidateUtil.isNotNull(orderInfo.getVerifyCode())) {
            OrderInfoMemory.getInstance().removeVerifyCode(orderInfo.getOrderNo(), orderInfo.getVerifyCode());
        }
        //修改订单信息缓存
        OrderInfoMemory.getInstance().modifyStatus(orderNo);
        //修改订单状态信息缓存
        OrderStatusMemory.getInstance().addStatus(orderNo);
        return AjaxResult.successResult();
    }

    // 二级骑手确认送达
    //二级骑手确认送达  即已完成等待用户确认
    @RequestMapping(method = RequestMethod.POST, value = "/secondary/postman/order/finish")
    @ResponseBody
    public String order_secondary_postman_finish(String token, String sysAppKey,
                                                 String orderNo,
                                                 Double lat, Double lng, String province, String city, String county, String address) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (ValidateUtil.isNull(orderNo)) {
            return AjaxResult.errorResult("请选择订单");
        }
        OrderInfo orderInfo = OrderInfoMemory.getInstance().getOrderInfo(orderNo);
        if (null == orderInfo) {
            return AjaxResult.errorResult("该订单不存在");
        }
        CityPostman postman = CityPostmanMemory.getInstance().getPostman(user.getUsername());
        if (postman == null) {
            return AjaxResult.errorResult("获取骑手信息错误");
        }
        if (postman.getType() == null || postman.getType() != POSTMAN_TYPE.POSTMAN_2) {
            return AjaxResult.errorResult("您不是众包端骑手");
        }

        if (StringUtils.isEmpty(orderInfo.getSecondaryPostManUsername()) || !orderInfo.getSecondaryPostManUsername().equalsIgnoreCase(user.getUsername())) {
            return AjaxResult.errorResult("该订单不属于您");
        }
        if (null != SYS_SETTINGS.POSTMAN_MUST_DEPOSIT && 0 == 1 - SYS_SETTINGS.POSTMAN_MUST_DEPOSIT) {
            // 必须缴纳
            //验证押金金额是否满足
            UserWallet userWallet = UserWalletMemory.getInstance().getWallet(user.getUsername());
            if (null == userWallet) {
                return AjaxResult.errorResult("您还未缴纳押金，请先缴纳押金");
            }
            if (null == userWallet.getDepositMoney() || userWallet.getDepositMoney() <= 0) {
                return AjaxResult.errorResult("您还未缴纳押金，请先缴纳押金！");
            }
            //必须缴纳的押金金额
            Double money = SysConfigDepositMemory.getInstance().getByType(UserType.POSTMAN);
            if (null == money) {
                money = 0d;
            }
            if (JYMathDoubleUtils.sub(userWallet.getDepositMoney(), money) < 0) {
                return AjaxResult.errorResult("您缴纳的押金不足，请先缴纳押金");
            }
        }
        //判断订单状态是否可以操作
        if (ORDER_STATUS.SECONDARY_POSTMAN_PULL_GOODS != orderInfo.getOrderStatus()) {
            return AjaxResult.errorResult("请先取货");
        }

        Long time = DateUtils.getCurrTime();
        //修改数据库
        StringBuilder sb = new StringBuilder();
        sb.append("update ").append(PojoTables.OrderInfo).append(" set orderStatus = ").append(ORDER_STATUS.POSTMAN_FINISH)
                .append(",updateUser='").append(user.getUsername()).append("',postmanFinishTime=").append(time)
                .append(" where delFlag=0 and orderNo = '").append(orderNo).append("'");
        OrderStatus orderStatus = new OrderStatus(orderNo, ORDER_STATUS.POSTMAN_FINISH, user.getUsername(), time);
        try {
            UserDaoSql.getInstance().insertObj(PojoTables.OrderStatus, orderStatus);
            UserDaoSql.getInstance().executeBySql(sb.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("操作失败，请稍后重试");
        }

        //修改订单状态缓存
        OrderStatusMemory.getInstance().addStatus(orderNo);
        //修改缓存
        OrderInfoMemory.getInstance().modifyStatus(orderNo);
        //更新二级骑手以备分成
        OrderPay.updateDistributeSecondaryMoney(orderInfo, orderNo, orderInfo.getSecondaryPostManUsername());
        //分成
        if (null != orderInfo.getOrderType() && 0 != ORDER_TYPE.SERVICE_LOCK - orderInfo.getOrderType()) {
            ResultInfo resultInfo = OrderPay.distributeMoney(orderInfo, orderNo, user.getUsername());
            if (null != resultInfo && !resultInfo.isSuccess()) {
                System.out.println("完成订单，但是分成失败：" + resultInfo.getError());
            }
            OverOrderThread.map.put(orderNo, orderInfo);//加入自动完成线程，超时未确认的  系统确认完成
        }
        // 删除验证码
        if (ValidateUtil.isNotNull(orderInfo.getVerifyCode())) {
            OrderInfoMemory.getInstance().removeVerifyCode(orderInfo.getOrderNo(), orderInfo.getVerifyCode());
        }
        //保存配送员确认送达位置
        if (ValidateUtil.isLatLng(lat, lng)) {
            OrderOtherInfo info = new OrderOtherInfo();
            info.setOrderNo(orderNo);
            info.setLat(lat);
            info.setLng(lng);
            info.setProvince(province);
            info.setCity(city);
            info.setCounty(county);
            info.setAddress(address);
            info.setCreateTime(time);
            info.setDelFlag(0);
            info.setCreateUser(user.getUsername());
            try {
                UserDaoSql.getInstance().insertObj(PojoTables.ORDER_OTHER, info);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (null != orderInfo.getOrderType() && 0 != ORDER_TYPE.SERVICE_LOCK - orderInfo.getOrderType()) {
            Notice.publishNotice2Person(sysAppKey, orderInfo.getUsername(), JPushMessage.USER, NoticeType.order, "订单信息", "您的订单（订单编号：" + orderNo + "），配送员已确认送达，请尽快确认订单完成");
        }
        return AjaxResult.successResult();
    }

    // 骑手送达提货点
    @RequestMapping(method = RequestMethod.POST, value = "/postman/order/point")
    @ResponseBody
    public String order_postman_post_point(String token, String orderNo, Double lat, Double lng, String province, String city, String county, String address) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        CityPostman postman = CityPostmanMemory.getInstance().getPostman(user.getUsername());
        if (null == postman) {
            return AjaxResult.errorResult("未查询到您的信息，无法操作");
        }
        //0 锁定  1未锁定
        if (null != postman.getIsLock() && 0 == 1 - postman.getIsLock()) {
            return AjaxResult.errorResult("您已被锁定，无法接单");
        }

        if (ValidateUtil.isNotAbsInteger(postman.getIsWork())) {
            return AjaxResult.errorResult("您无法接单，请先上班");
        }
        if (0 == postman.getIsWork()) {
            return AjaxResult.errorResult("请先上班");
        }
        if (null != SYS_SETTINGS.POSTMAN_MUST_VERIFY && 0 == 1 - SYS_SETTINGS.POSTMAN_MUST_VERIFY
                && (null == postman.getIsVerify() || 0 != 1 - postman.getIsVerify())) {
            return AjaxResult.errorResult("您尚未通过认证，请先去认证");
        }
        if (null != SYS_SETTINGS.POSTMAN_MUST_VERIFY_FACE && 0 == 1 - SYS_SETTINGS.POSTMAN_MUST_VERIFY_FACE) {
            if (null != user.getIsCert() && 0 == 1 - user.getIsCert()) {
                //已认证
            } else {
                return AjaxResult.errorResult("未通过实名认证，请先去认证");
            }
        }

        OrderInfo orderInfo = OrderInfoMemory.getInstance().getOrderInfo(orderNo);
        if (null == orderInfo) {
            return AjaxResult.errorResult("当前订单不存在");
        }

        Long time = DateUtils.getCurrTime();
        String postmanPostPointTimeStr = "";
        postmanPostPointTimeStr = ",postmanPostPointTime = " + time;
        if (!OrderMan.modifyOrderStatus(user.getUsername(), orderNo, ORDER_STATUS.POSTMAN_PICK_POINT, postmanPostPointTimeStr)) {
            return AjaxResult.errorResult("操作失败，请稍后重试");
        }

        // 更新骑手 以备分成
        updateOrderPayPostman(orderNo, user.getUsername(), user.getUsername());

        //保存一级配送员确认送达位置
        if (ValidateUtil.isLatLng(lat, lng)) {
            OrderOtherInfo info = new OrderOtherInfo();
            info.setOrderNo(orderNo);
            info.setLat(lat);
            info.setLng(lng);
            info.setProvince(province);
            info.setCity(city);
            info.setCounty(county);
            info.setAddress(address);
            info.setCreateTime(time);
            info.setDelFlag(0);
            info.setCreateUser(user.getUsername());
            try {
                UserDaoSql.getInstance().insertObj(PojoTables.ORDER_OTHER, info);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        // 成功
        return AjaxResult.successResult();
    }


    //---------------------------
    // 是否可以抢单
    private static boolean canGrabOrder(String username, Long agentId, String orderNo) {
        boolean runNewRule = false;
        OrderInfo orderInfo = OrderInfoMemory.getInstance().getOrderInfo(orderNo);
        int postmanCanGrabOrder = -1;// 骑手可抢单数量
        // 查询骑手已接单数
        int count = PostmanOrderMemoryMan.getPostmanIngOrderCount(username);
        // 查询门店, 获取门店最大可接单数
        ShopInfo shop = ShopMemory.getInstance().getShopByUsername(orderInfo.getUsername());
        if (shop == null) {
            shop = ShopMemory.getInstance().getShopById(orderInfo.getShopId());
        }
        if (shop != null && StringUtils.isNotEmpty(shop.getPostmanMaxOrder())) {
            String postmanMaxOrder = shop.getPostmanMaxOrder();
            postmanCanGrabOrder = Integer.parseInt(postmanMaxOrder) ;
        } else {
            // 骑手按商圈管理
            if (null != SYS_SETTINGS.POSTMAN_IN_CITY_OR_AGENT && 0 == SYS_SETTINGS.POSTMAN_IN_CITY_OR_AGENT - POSTMAN_IN_CITY_OR_AGENT_DATA.AGENT) {
                // 获取订单所在商圈
                boolean isAgentSettings = false;// 是否使用商圈的设置
                if (ValidateUtil.isID(agentId)) {
                    OrderOverTimeInfo overTimeInfo = AgentOrderOverTimeMemory.getInstance().getAgentOrderOverTimeInfoByAgentId(agentId);
                    if (null != overTimeInfo) {
                        postmanCanGrabOrder = overTimeInfo.getPostmanCanGrabOrder();
                        isAgentSettings = true;
                    }
                }
                if ((isAgentSettings && postmanCanGrabOrder > 0) || (null != SYS_SETTINGS.POSTMAN_CAM_GRAB_ORDER && SYS_SETTINGS.POSTMAN_CAM_GRAB_ORDER > 0)) {
                    count = PostmanOrderMemoryMan.getPostmanIngOrderCount(username);
                    if (isAgentSettings) {
                        if (count - postmanCanGrabOrder >= 0) {
                            return false;
                        }
                    } else {
                        if (count - SYS_SETTINGS.POSTMAN_CAM_GRAB_ORDER >= 0) {
                            return false;
                        }
                    }
                }
            } else {
                if (null != SYS_SETTINGS.POSTMAN_CAM_GRAB_ORDER && SYS_SETTINGS.POSTMAN_CAM_GRAB_ORDER > 0) {
                    count = PostmanOrderMemoryMan.getPostmanIngOrderCount(username);
                    if (count - SYS_SETTINGS.POSTMAN_CAM_GRAB_ORDER >= 0) {
                        return false;
                    }
                }
            }
        }
        // 如果已接单数大于可接单数 返回false
        if (count - postmanCanGrabOrder >= 0) {
            return false;
        }
        return true;
    }


//    // 修改订单的信息公司钱等信息
//
//    private static void updateOrderCompanyDeliveryPrice(Long companyId, String postmanUsername, OrderInfo orderInfo, String opUser, Connection conn) throws Exception {
//        if (orderInfo == null || conn == null) {
//            throw new Exception("信息不全");
//        }
//        if (SYS_SETTINGS.CUSTOM_SYSTEM_TYPE != null && SYS_SETTINGS.CUSTOM_SYSTEM_TYPE == 1) {
//            StringBuilder sb = new StringBuilder();
//            sb.append("update ").append(PojoTables.OrderInfo).append(" set updateUser='").append(opUser).append("'");
//            ShopSignCompanyFeeInfo info = ShopSignCompanyService.getInstance().get(companyId, orderInfo.getShopId(), orderInfo.getOrderType());
//            Double baseDeliveryPrice = 0.0d;
//            Double fcDeliveryPrice = 0.0d;
//            if (info == null) {
//                // 默认到平台的
//                baseDeliveryPrice = orderInfo.getDeliveryPrice();
//                fcDeliveryPrice = orderInfo.getDeliveryPrice();
//            } else {
//                baseDeliveryPrice = info.getPrice();
//                if (baseDeliveryPrice >= orderInfo.getDeliveryPrice()) {
//                    fcDeliveryPrice = baseDeliveryPrice;
//                } else {
//                    fcDeliveryPrice = orderInfo.getDeliveryPrice();
//                }
//            }
//            sb.append(",baseDeliveryPrice=").append(baseDeliveryPrice)
//                    .append(",fcDeliveryPrice=").append(fcDeliveryPrice);
//            // 分成等计算
//            DeliverCompanySalarySerivce.SalaryDisributeTO salaryDisributeTO = DeliverCompanySalarySerivce.getInstance().getDeliverMoney(companyId, postmanUsername, orderInfo.getDeliveryPrice());
//            sb.append(",companyAllowance = ").append(salaryDisributeTO.getAllowance());
//            // 分成添加一条
//            OrderPayInfo orderPayInfo = OrderPayMemory.getInstance().get(orderInfo.getOrderNo());
//            if (orderPayInfo == null) {
//                OrderPayInfo orderPay = new OrderPayInfo();
//                orderPay.setCreateTime(DateUtils.getCurrTime()).setDelFlag(0);
//                UserDaoSql.getInstance().saveObj(PojoTables.OrderPay, orderPay, conn);
//            } else {
//
//
//
//
//
//            }
//
//
//        }
//
//    }

}
